Django - 表单FileField错误“此字段是必需的”

时间:2017-07-25 17:00:45

标签: python django django-forms

我想将Post表单添加到我的django项目中,我遇到了FileFiled的问题。这是我的代码:

forms.py

class PostForm(forms.ModelForm):

   class Meta:
      model = Post
      fields = [
        'author',
        'image',
        'title',
        'body'
    ]

models.py

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    image = models.FileField(default="", blank=False, null=False)
    title = models.CharField(max_length=200)
    body = models.TextField()
    date = models.DateTimeField(default=timezone.now, null=True)

    def approved_comments(self):
        return self.comments.filter(approved_comment=True)

    def __str__(self):
        return self.title

如果有帮助的话。我还在enctype="multipart/form-data

中设置了<form>

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

来自docs

您需要将request.FILES传递给绑定表单。

bound_form = PostForm(request.POST, request.FILES)

答案 1 :(得分:3)

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    image = models.FileField(upload_to='path')
    title = models.CharField(max_length=200)
    body = models.TextField()
    date = models.DateTimeField(default=timezone.now, null=True)

    def approved_comments(self):
        return self.comments.filter(approved_comment=True)

    def __str__(self):
        return self.title

您需要在文件字段中提及upload_path

enctype="multipart/form-data添加到您的表单

并且为了获取文件

PostForm(request.POST, request.FILES)

如果你需要使字段可选

class PostForm(forms.ModelForm):
image = forms.FileField(required=False)
   class Meta:
      model = Post
      fields = [
        'author',
        'image',
        'title',
        'body'
    ]