How to redirect with messages to display them in Django Templates?

Viewed 56126

I have a view that validates and saves a form. After the form is saved, I'd like redirect back to a list_object view with a success message "form for customer xyz was successfully updated..."

HttpResponseRedirect doesn't seem like it would work, because it only has an argument for the url, no way to pass dictionary with it.

I've tried modifying my wrapper for object_list to take a dict as a parameter that has the necessary context. I the return a call to this wrapper from inside the view that saves the form. However, when the page is rendered, the url is '/customer_form/' rather than '/list_customers/'. I tried modifying the request object, before passing it to the object_list wrapper, but that did not work.

Thanks.

6 Answers

I found the following to work if more than just a message needs to be added to the redirect:

from django.shortcuts import redirect
import urllib

def my_view(request):

    ...

    context = {'foo1': bar1, 'foo2': bar2, 'foo3': bar3}
    return redirect('/redirect_link/?' + urllib.parse.urlencode(context))

See also how to pass context data with django redirect function?

In Django 2.x + you can simply use messages framework that comes with Django

views.py

from django.contrib import messages

def register(request):
    ....
    messages.success(request,"You have registered successfully, now login!")
    return redirect('login-page')

And in you, login.html template do add this code

  {% if messages %}
    {% for message in messages %}
        <div class="alert alert-success alert-dismissible fade show">
            <strong>Success!</strong> {{message}}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    {% endfor %}
 {% endif %}

Note this example can be applied to anywhere you want to display a message for success

If you want to pass an error message simply use messages.error(request, "Error message")

To Django Admin, I could redirect with the several types of messages as shown below:

# "views.py"

from django.contrib import messages # Here
from django.shortcuts import redirect

def my_view(request): 
    messages.debug(request, 'This is debug')
    messages.info(request, 'This is info')
    messages.success(request, 'This is success')
    messages.warning(request, 'This is warning')
    messages.error(request, 'This is error')
    return redirect("http://localhost:8000/admin/store/order/")

But, I don't know why only "debug" message is not displayed even though "DEBUG = True" in "settings.py":

enter image description here

Related