Django redirect with custom context

Ayush Goyal
Sep 1, 2018 · 1 min read

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store