I'm not sure if what I'm doing is right or wrong. But this functionality brought me across a very esoteric event happening inside Django Views.
So the code:
from django.contrib.messages import get_messages
from django.contrib import messages
#Other required modules.
@require_GET
def get_form(request):
#code to get a form.
storage = get_messages(request)
for message in storage:
message = message
if message:
context['message'] = message
html = render(request , 'some_html.html' , context)
return HttpResponse(html)
@require_POST
def submit_form(request):
#Initialize a bounded form.
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, success_message)
else:
messages.add_message(request, messages.INFO, error_message)
# ABOVE LINE IS WHERE THE ISSUE OCCURS
return redirect('reverse_url_mapping_to_get_form')
# Above line is redirecting to "get_form" function(The function preceding this one).
ISSUE : Now the strange thing I encountered occurred when I made a typo in return redirect('reverse_url_mapping_to_get_form')
(The last line of the code mentioned.).
Obviously I encountered Django's error page, saying that there is "NoReverseMatch". But when I reloaded the form(normal refreshing through the browser, on the "url" mapping to get_form(request)
), I found that the error message which I added in the line messages.add_message(request, messages.INFO, error_message)
was being brought to the html(some_html.html). Even thought the error occurred and I never redirected to the url successfully.
Now I understand that messages.add_message()
somewhat piggybacks on the request, BUT, shouldn't it have been destroyed in the case when error occurred. The case where the redirect wasn't successfully executed.
Why did the message was still inside the request object when the reload occur?
Shouldn't it have been destroyed(because it was a completely independent GET request; I initiated it from my browser by reloading)?
Thanks in advance.