Search code examples
djangodjango-forms

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


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.


Solution

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