Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Form FileField error "This field is required"

I want to add Post form into my django project and I've got problem with FileFiled. Here is my code:

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

If it helps. I also set enctype="multipart/form-data in <form>

Thanks for help.

like image 895
jestembotem Avatar asked Nov 29 '22 22:11

jestembotem


2 Answers

From the docs

You need to pass request.FILES to the bound form.

bound_form = PostForm(request.POST, request.FILES)
like image 61
Iain Shelvington Avatar answered Dec 05 '22 12:12

Iain Shelvington


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

you need to mention the upload_path in the filefield

add enctype="multipart/form-data to your form

and in view to get the files

PostForm(request.POST, request.FILES)

if you need to make the field optional

class PostForm(forms.ModelForm):
image = forms.FileField(required=False)
   class Meta:
      model = Post
      fields = [
        'author',
        'image',
        'title',
        'body'
    ]
like image 41
Exprator Avatar answered Dec 05 '22 14:12

Exprator