How can I delete a request.session variable inside the Django HTML template?

Issue

Code:

{% if request.session.message %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <i class="bi bi-check2-circle"></i> {{request.session.message}}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endif %}
{% request.session.remove('message') %}

Error:

TemplateSyntaxError at /
Could not parse the remainder: ‘(‘message’)’ from ‘request.session.remove(‘message’)

Solution

You are using the sessions mechanism to post messages to a user, but Django already has tools for that in place: Django’s messages framework. In fact the default storage mechanism of these messages are the session variables.

The messages framework however makes it easy to let Django do bookkeeping about what messages the user has seen, and makes it easy to deliver multiple messages to the user. Furthermore one can give the messages a certain severity level.

You install the messages framework by specifying as MIDDLEWARE setting [Django-doc] both 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.messages.middleware.MessageMiddleware'. Furthermore the 'django.contrib.messages' app should be in in INSTALLED_APPS setting [Django-doc]. this is by default already the case, and for the TEMPLATES setting [Django-doc], you should add 'django.contrib.messages.context_processors.messages' to the 'context_processors' key, so the settings should look like:

# settings.py

# …

MIDDLEWARE = [
    # …,
    'django.contrib.sessions.middleware.SessionMiddleware',
    # …,
    'django.contrib.sessions.middleware.MessageMiddleware'
    # …
]

# …

INSTALLED_APPS = [
    # …,
    'django.contrib.messages',
    # …
]

# …

TEMPLATES = [
    {
       # …,
       'context_processors': [
           # …,
           'django.contrib.messages.context_processors.messages'!!!,
           # …
       ]
       # …
    }
]

# …

You can then add a message to the request object with:

from django.contrib import messages

# …

messages.warning(request, 'Some warning')

Then in the template, you can render the messages with:

{% for message in messages %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <i class="bi bi-check2-circle"></i> {{ message }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published