Django redirect with custom context
While working on a recent Django project, I was stuck when I needed to send custom context in redirect request. I googled a lot and still didn’t find any way to do so. Hence I devised my way to do so.
This blog is more of a reminder of how I managed to do so.
Since you are facing this issue, I am assuming you have a basic idea on the working of Django. So, we will not go into details.
Assuming you following two views in your views file.
def view1(request) :
..
context = {
..
}
..
return render(request, "../../xyz.html", context=context)def view2(request) :
..
context = {
..
}
..
return render(request, "../../abc.html", context=context)
Now, if you want to redirect to view1 from view2 along with its context, you can modify your functions like this.
def view1(request, newContext={}) :
..
..
context = {
..
}
context.update(newContext)
..
return render(request, "../../xyz.html", context=context)
def view2(request) :
..
context = {
..
}
..
response = view1(request, context)
return response
So, what happens here is, since in view1 the newContext parameter is already initialised, the normal calling of it in the Django architecture will not be hampered and the context.update(newContext) has no effect and when view2 calls view1, a response is returned so it can be directly returned from view2.
Note that this will not change the URL.