Django Forms: if not valid, show form with error message

user984003 picture user984003 · Feb 1, 2013 · Viewed 172.4k times · Source

In Django forms, it can check whether the form is valid:

if form.is_valid(): 
    return HttpResponseRedirect('/thanks/')

But I'm missing what to do if it isn't valid? How do I return the form with the error messages? I'm not seeing the "else" in any of the examples.

Answer

Aamir Adnan picture Aamir Adnan · Feb 1, 2013

If you render the same view when the form is not valid then in template you can access the form errors using form.errors.

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

An example:

def myView(request):
    form = myForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    return render(request, 'my_template.html', {'form': form})