Barium Scoorge
Barium Scoorge

Reputation: 2008

Correctly pass view errors to template with Django

How can I pass errors to display them in templates, using a clean and common way ?

I'd like to show errors through an overlay box message.

I'm confused when using HttpResponseRedirect ; unless using session variables, it's not possible to pass errors.

Upvotes: 2

Views: 4425

Answers (1)

Thibault J
Thibault J

Reputation: 4446

The usual way is to use Django's message framework, like Rohan said.

Anywhere in your view, you can use this code to pass errors to the templates :

from django.contrib import messages


def my_view(request):
    …
    messages.error(request, 'Oops, something bad happened')
    return redirect…

You can add the following code in your base.html template to display those messages (here using bootstrap classes):

{% if messages %}
<div class="span12">
{% for message in messages %}
    <div class="alert alert-{{ message.tags }}">
        {{ message|safe }}
    </div>
{% endfor %}
</div>
{% endif %}

Upvotes: 13

Related Questions