我有一个Post
模型供用户提交帖子。我已将content
字段Post
赋予blank=True
属性。但由于某种原因,django告诉我content
仍然是必需的。 form_post.errors
打印出来:
<ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
这是我的代码:
模型
class Post(models.Model):
...
user = models.ForeignKey(User, blank=True, null=True)
title = models.TextField(max_length=76)
content = models.TextField(null=True, blank=True)
category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1')
形式
class PostForm(forms.ModelForm):
content = forms.CharField(widget=PagedownWidget)
title = forms.TextInput(attrs={'placeholder': 'title'})
class Meta:
model = Post
fields = [
'title',
'content',
'category',
'image',
'id',
'user'
]
视图
def post(request):
allauth_login = LoginForm(request.POST or None)
allauth_signup = SignupForm(request.POST or None)
if request.user.is_authenticated():
form_post = PostForm(request.POST or None, request.FILES or None)
if form_post.is_valid():
print('valid')
instance = form_post.save(commit=False)
instance.user = request.user
category = form_post.cleaned_data['category']
for a, b in CATEGORY_CHOICES:
if a == category:
category = b
form_post.save()
return HttpResponseRedirect('/%s' % category)
else:
print(form_post.errors)
form_post = PostForm()
context = {
'allauth_login': allauth_login,
'allauth_signup': allauth_signup,
'form_post': form_post
}
return render(request, 'post.html', context)
else:
return HttpResponseRedirect("/accounts/signup/")
HTML
...
<form method="post" action="" enctype="multipart/form-data">{% csrf_token %}
<div class="submitContainer">
<div class="article_title_div">
{{ form_post.title|add_class:"article_title" }}
</div>
<div>
</div>
{{ form_post.category }}
</div>
<div class="submitButton">
<button class="submitArticleSubmit" type="submit">Post</button>
</div>
</form>
...
知道我为什么会收到此错误?
答案 0 :(得分:1)
原因是因为你是overriding the default model field
。 content
和title
。
虽然content
存储在您的数据库中时可以为空,但您的表单required
为content = forms.CharField(widget=PagedownWidget)
。
更改为content = forms.CharField(widget=PagedownWidget, required=False)
,使其在表单提交时可选。