How to display a message in Django after a post was submitted?

Suppose we have a post and after we send it, we want to display a message to the user in which to tell him “The message was submitted!”.

Django provides full support for cookie and session-based messaging, for both anonymous and authenticated users.

Every message is tagged with a specific level that determines its priority (e.g., success, info, warning, or error). All You need is to use messages from django.contrib

Read more here about The messages framework in Django

How to use messages from django.contrib in views.py

First You need to import messages from django.contrib in Your views.py

After, You can use message.success as in the code below, a form from the contact page with Google ReCaptcha:

from django.contrib import messages

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

        if form.is_valid():
            subject = 'Message from contact form'
            from_email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            messages.success(request, 'Message was sent!')
            try:
                send_mail(subject, message, from_email,
                          ['your_email@gmail.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return HttpResponseRedirect(request.path_info)
        else:
            return HttpResponse("OOPS! Bot suspected")

    else:
        form = ContactForm()

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

Show the messages in Your template

You can display the messages in your template as:

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

Contact form example in forms.py

The contact form in forms.py look like:

class ContactForm(forms.Form):
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)

Leave a Comment

How to? Ask a Question