'How can I delete a request.session variable inside the Django HTML template?
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 1:[1]
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 %}
Solution 2:[2]
For people who wants to clear the session storage from Django templates [Not just messages]
index.html
<form action="/" method="get">
<input type="button" name="clear" hidden="True">
<input type="submit" value="clear session">
</form>
views.py
def index(request):
if request.method == 'GET':
if "clear" in dict(request.GET):
request.session = {}
return render(request, 'index.html')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Willem Van Onsem |
Solution 2 | Aditya Rajgor |