0
我有用於提交帖子的用戶的Post
模型。我已經給出content
字段Post
屬性blank=True
。但由於某種原因Django告訴我content
仍然是必需的。 form_post.errors
打印此:儘管我設置了null = True並且空白= True,但獲取「此字段是必需的」錯誤
<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>
...
任何想法,爲什麼我得到這個錯誤?
設置完'blank = True'和'null = True'後,你有'./manage.py makemigrations'和'./manage.py migrate',不是嗎? –
是的我已經完成了兩個 – Zorgan
這是因爲你正在重寫'PostForm'內的'content'('content = forms.CharField(widget = PagedownWidget)',在其中放置一個'required = False'。 –