我想将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>
感谢您的帮助。
答案 0 :(得分:3)
答案 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'
]