即使我设置null = True和blank = True,也会出现“此字段是必需的”错误

时间:2017-04-03 06:14:26

标签: python django django-forms

我有一个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>
...

知道我为什么会收到此错误?

1 个答案:

答案 0 :(得分:1)

原因是因为你是overriding the default model fieldcontenttitle

虽然content存储在您的数据库中时可以为空,但您的表单requiredcontent = forms.CharField(widget=PagedownWidget)

更改为content = forms.CharField(widget=PagedownWidget, required=False),使其在表单提交时可选。