How to pass context data with django redirect function?

Question:

I have function which redirect to a URL.

return redirect('/orders')

The URL /orders has some context data which is being passed to it.
I want to pass some additional data along with data from the URL’s function in view like:

return redirect('/orders', {'message':'some_message'})

I tried like this according to documentation:

return redirect('/orders', message='some_message')

But it didn’t passed any data back to html.
So how to pass data with redirect?

Asked By: Manish Gupta

||

Answers:

If you are using http redirect (the case you mentioned), you need to pass your arguments through url’s query string:

redirect('/orders?message=some_message')

Another ways is that you call other view with your custom parameter, which is not recommended generally.

Edit:
You can also use django.sessions to make central request-based messaging.

Answered By: kia

If its just a small item, like ?status=2 it can be added to the URL in the usual way. (small aside: careful, it may have a negative impact of how search engines spider your web site, i.e. create duplicate content issues)

However, for your example, passing an entire “message” string to the next page, I would recommend to do it the same way Django’s Messages framework does it: by using Django’s Session engine.

Answered By: C14L

I mean you can always use the get_context_data method to do that. This method will always sent the data from the view to the template.

Answered By: Mohammad Mahjoub

You can redirect with post data using request.session["key"] as shown below:

# "views.py"

from django.shortcuts import redirect

def my_view(request): 
            # Here
    request.session["message"] = "some_message"
    return redirect('/orders')
# "index.html"

{{ request.session.message }} {# some_message #}
Answered By: Kai – Kazuya Ito