Tried tonnes of stuff out there but none of them really helped.
I have a URL
for example:
which calls the below view
:
def edit_transaction(request):
if request.method == "POST":
if something is True:
messages.error(request, 'Error message here')
# this don't work
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
# but this work
template = "user/xyz/abc.html"
render(request, template)
else:
return HttpResponseNotFound()
else:
context = {
'key1': 'value1',
'key2': 'value2',
}
template = "user/xyz/abc.html"
render(request, template, context)
And inside template:
{% if messages %}
<h1>I am inside MESSAGES</h1>
{% for message in messages %}
{% if message.tags == 'success' %}
<div class="alert alert-success" role="alert">{{ message|escape|safe }}</div>
{% elif message.tags == 'error' %}
<div class="alert alert-danger" role="alert">{{ message|escape|safe }}</div>
{% endif %}
{% endfor %}
{% endif %}
It's getting inside the if
here if something is True:
and getting redirected to the same page with the query string as well. But not displaying the error message.
What I want is to redirect to the same page preserving the query string and display the error message. What am I doing wrong here and what changes are recommended (if any).
Also a doubt, that does Django messages really work after redirection like Flash messages should ??
Edit:
1) This don't work:
if something is True:
messages.error(request, 'Error message here')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
From console:
[16/Sep/2015 10:57:08]"POST /user/edit-transaction/?object_id=23a959d0561711e59e36acd1b8679265&type=grossary HTTP/1.1" 302 0 [16/Sep/2015 10:57:08]"GET /user/edit-transaction/?object_id=23a959d0561711e59e36acd1b8679265&type=grossary HTTP/1.1" 200 8832
2) This works:
if something is True:
messages.error(request, 'Error message here')
template = "user/xyz/abc.html"
render(request, template)
From console:
[16/Sep/2015 10:57:08]"POST /user/edit-transaction/?object_id=23a959d0561711e59e36acd1b8679265&type=grossary HTTP/1.1" 302 0
So, basically what I understood from above is that the messages
is getting expired with an additional request (redirect, 200).
And in templates, it is not getting inside the {% if messages %}
as well to print <h1>I am inside MESSAGES</h1>