Django Messages Example


Django tip:

For displaying a one-time notification message, you can use Django's built-in messages framework.

(The default settings.py file created with startproject contains all the required settings.)

For example, your view and template file would look something like this:

# views.py

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

        if form.is_valid():
            form.save()

            messages.success(request, "Your message was sent.") # message

            return redirect("cart")

    form = ContactForm(request.POST)
    return render(request, "contact.html", {"form": form})


# contact.html

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