Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass context data with django redirect function?

Tags:

python

django

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?

like image 591
Manish Gupta Avatar asked Jan 02 '16 08:01

Manish Gupta


People also ask

Can we pass context in redirect in Django?

I would use session variables in order to pass some context through a redirect. It is about the only way to do it outside of passing them as part of the url and it is the recommended django option.

How pass data redirect Django?

Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .

What is the difference between HttpResponseRedirect and redirect?

There is a difference between the two: In the case of HttpResponseRedirect the first argument can only be a url . redirect which will ultimately return a HttpResponseRedirect can accept a model , view , or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


1 Answers

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.

like image 115
C14L Avatar answered Oct 17 '22 13:10

C14L