【问题标题】:Django Image Field not Updating on the FrontDjango 图像字段未在前面更新
【发布时间】:2016-02-18 00:07:19
【问题描述】:

我正在尝试让我的应用程序验证我的应用程序模板中的图片上传字段并保存上传的任何新图片。在管理方面一切正常,但是当我在前面进行图像更改时,它不会被保存。

这是我的模型

def imageupload(instance, filename):
    return os.path.join('static/petition-photos/', filename)

# Create your models here.

class Petition(models.Model):
    title = models.CharField(max_length= 90, default="Enter petition title here")
    created_on = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(null=False, upload_to=imageupload)
    video = models.CharField(max_length=600, default="Enter an external video link")
    petition = models.TextField(null=False, default="Type your petition here")
    created_by = models.ForeignKey(User)

这是我的视图类:

class NewPetitionView(generic.edit.CreateView):
model = Petition
template_name = 'petition/petition_form.html'
fields= ['title','petition', 'image', 'video']
success_url = '/dashboard/'

def form_valid(self, form):
    form.instance.created_by = self.request.user
    return super(NewPetitionView, self).form_valid(form)

这是我的表单模板:

{% include 'layout/header.html' %}

{% block content %}
    <form action="" method="post">
        {{form.as_p}}
        <button type="submit">Submit</button>
        {% csrf_token %} 
    </form>
{% endblock %}

当我将图片上传到新帖子或尝试编辑其中一个已发布项目的图片字段时,我会收到“此字段为必填项”通知。

我做错了什么?

【问题讨论】:

    标签: python django python-3.x django-forms django-templates


    【解决方案1】:

    您需要在您的&lt;form&gt; 添加enctype="multipart/form-data" 才能让文件上传工作。

    &lt;form action="" method="post" enctype="multipart/form-data"&gt;

    django doc.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 2015-12-05
      • 2020-03-06
      • 1970-01-01
      • 2012-03-22
      • 2015-11-16
      • 1970-01-01
      相关资源
      最近更新 更多