Last modified: Jan 10, 2023 By Alexander Williams

Understand How to Use django HttpResponseRedirect with Examples

Django HttpResponseRedirect is a subclass of HttpResponse that redirects the user to a specific URL.
In this tutorial, we'll cover Django HttpResponseRedirect, so pay attention and let's get started.

1. Using HttpResponseRedirect with examples

Before talking about why we need to use HttpResponseRedirect, let's write a simple view to understand how it's working.


So first, we need to import HttpResponseRedirect:

fromdjango.httpimport HttpResponseRedirect


example #1:

views.py

#indexdefindex(request):
    return HttpResponse("<h1>Index Page</h1>")


#redirect userdefredirect_user(request):
    return HttpResponseRedirect('/index')

urls.py

#index
path('index/', index, name="index_page"),

#redirect
path('redirect/', redirect_user, name="redirect")

result:

Understand How to Use django HttpResponseRedirect with Examples

Let me explain:

We have 2 views index and redirect_user views, and the redirect_user view redirects us to index.

The question now is why we need HttpResponseRedirect?
For example, we want to redirect the user to a specific URL after submitting the form.


Example #2:

defredirect_user(request):
    if request.method =="POST":
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)

        if username and password:
            return HttpResponseRedirect('/index')

    return render(request, "form.html")  

result:

Understand How to Use django HttpResponseRedirect with Examples

2. Django HttpResponseRedirect with Reverse function

If you want to use the URL tag instead of the URL, you should use the reverse function with HttpResponseRedirect.
Let's see an example.


urls.py

#index
path('index/', index, name="index_page"),

views.py

defredirect_user(request):
    return HttpResponseRedirect(reverse('index_page'))

result:

Understand How to Use django HttpResponseRedirect with Examples



3. How to solve HttpResponseRedirect is not defined

issue output:

Understand How to Use django HttpResponseRedirect with Examples

To solve this issue, you simply need to import the subclass like:

fromdjango.httpimport HttpResponseRedirect