Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to display form errors in Django when using the GET method is by using the messages framework.

First, import the messages module in your views.py file:

from django.contrib import messages

Next, in the view function that handles the GET request with the form submission, check if the form is valid. If the form is not valid, add an error message to the messages framework and redirect back to the same form page using the redirect() function:

from django.shortcuts import render, redirect
from .forms import MyForm

def my_view(request):
    if request.method == 'GET':
        form = MyForm(request.GET)
        if form.is_valid():
            # process form data
            return redirect('success')
        else:
            messages.error(request, 'Please correct the errors below.')
            return redirect('my_form_page')
    else:
        form = MyForm()

    return render(request, 'my_template.html', {'form': form})

In the HTML template for the form page (e.g. my_template.html), you can display any messages using the {% messages %} template tag:

{% if messages %}
    <ul class="messages">
    {% for message in messages %}
        <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
    </ul>
{% endif %}

<form method="get">
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

This will display any form errors in a red error message at the top of the form.