Aziz Alfoudari
Aziz Alfoudari

Reputation: 5263

Django - form.is_valid always returning true

I have the following form:

from django import forms

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

And the following view:

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))

I'm using Django 1.4, and according to the documentation the fields are by default required so I don't need to add required=True for each field.

For some reason, form.is_valid is always true. The Thank you for your feedback! message always appears when I submit the form even though form.name/email/message.errors is populated with errors! I have also tried explicitly setting required=True for each field, however it made no difference.

This is how I'm showing messages in contact.html:

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

Any idea what I'm doing wrong?

Upvotes: 1

Views: 1190

Answers (1)

lollo
lollo

Reputation: 2307

Replace

if form.is_valid:

to

if form.is_valid():

Upvotes: 4

Related Questions