Django - form.is_valid总是返回true

时间:2012-07-23 07:33:26

标签: django django-forms

我有以下表格:

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

以下观点:

def contact(request):
    from forms import ContactForm
    from django.contrib import messages

    if request.method == 'POST':
        form = ContactForm(request.POST)

        if form.is_valid:
            messages.success(request, 'Thank you for your feedback!')
        else:
            messages.error(request, 'Please correct the fields in red below.')

    else:
        form = ContactForm()

    t = loader.get_template('contact.html')
    c = RequestContext(request, {
        'ContactForm': form,
    })

    return HttpResponse(t.render(c))

我正在使用Django 1.4,根据文档,这些字段默认是必需的,因此我不需要为每个字段添加required=True

出于某种原因,form.is_valid始终是真的。即使Thank you for your feedback!填充了错误,我提交表单时也会始终显示form.name/email/message.errors消息!我也尝试为每个字段明确设置required=True,但它没有任何区别。

这就是我在contact.html中显示消息的方式:

{% for message in messages %}
    <div class="alert alert-{{ message.tags }}">{{ message }}</div>
{% endfor %}

知道我做错了吗?

1 个答案:

答案 0 :(得分:3)

替换

if form.is_valid:

if form.is_valid():