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.
From the docs
You need to pass request.FILES
to the bound form.
bound_form = PostForm(request.POST, request.FILES)
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'
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With