Reputation: 85
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.
Upvotes: 4
Views: 8716
Reputation: 27503
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'
]
Upvotes: 9
Reputation: 32244
From the docs
You need to pass request.FILES
to the bound form.
bound_form = PostForm(request.POST, request.FILES)
Upvotes: 12