Django - 表单 FileField 错误 "This field is required"

4

我希望在我的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"。
谢谢您的帮助。
2个回答

12

文档中得知:

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

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

我只是在解决一些其他问题,比如模型中的“upload_to”和HTML表单标记中的“enctype ='multipart/form-data'”之后才到这里,并且它正在工作。 - Fathy

9
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

您需要在filefield中提及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'
    ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接