【问题标题】:Save image file to Django Upon Submit Using CreateView CBV使用 CreateView CBV 提交时将图像文件保存到 Django
【发布时间】:2019-11-26 13:24:42
【问题描述】:

昨天,使用此解决方案View an Image Using Django CreateView Before Submitting 我能够弄清楚当用户单击我的 Django 项目中的选择文件按钮时如何显示图像。但是,我无法弄清楚当用户提交表单时如何保存图像。我意识到我正在使用的解决方案是利用 HTML URL 使用 Javascript 显示图像。

当我使用一种方法来附加图像然后提交表单而不首先显示图像时,这很好用。但是,当我使用上面提到的解决方案时,它不会捕获图像。

这行得通...

<div>
  <h2>Photo: </h2>
</div>

<div>
  {{ form.image }}
</div>

但是,当我尝试改用它时......从之前的解决方案......

<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />

并且使用 Javascript...

  function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        $('#blah')
          .attr('src', e.target.result)
          .width(150)
          .height(200);
      };
      reader.readAsDataURL(input.files[0]);
    }
  }

文件显示,但我不知道如何在用户提交时将其保存到数据库中。

我尝试使用此处记录的各种解决方案...Django: add image in an ImageField from image url 但到目前为止还没有运气。提前感谢您的任何想法。

【问题讨论】:

    标签: javascript django django-forms django-templates django-views


    【解决方案1】:

    原来如此简单!!!顺便说一句,当您知道答案时,这很简单..

    <input type='file' name="django_form_field_name" onchange="readURL(this);" />
    

    确保输入名称与 django 表单名称匹配是将图像 URL 获取到具有正确位置的数据库的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 2014-03-13
      • 2017-08-25
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多