How does redirect, HttpResponseRedirect, and render work in Django?

Share your love

The primary objective of a website is to create URL endpoints and pages that users can use to access the information on a website, whether the information is in the form of text, image, or multimedia.

Django is a perfect Python web framework used to create fast and functional web applications. The key functions and subclasses used in the creation of web pages on a Django project are the render(), redirect(), and HttpResponseRedirect().

These functions and subclasses play a great role in creating URLs and web pages on a Django web application. Moreover, they help a user navigate through the various sections of your web application.

Let’s dive right into each function and subclass and see how they connect and operate.

What is Django redirect, and how does the function work?

Suppose you may be asking how to redirect URLs in Django. Well, you just need to call the redirect() function in your Django views.

A redirect happens when you want to take a user to a particular URL that is different from the default URL. Also, when you have a new URL you want users to access instead of an outdated URL, you use the redirect() function.

However, if you were to delete the old URL, users or search engines may try to access the old URL, and they will receive a 404 error. Too many error pages for an established website may affect your SEO or lead to frustration for your users if the page they were accessing was important, but they cannot access it.

A better approach is to retain the old URL. But, when a user accesses the old URL, they do not get a page not found error, but they are automatically redirected to a new URL.

So, instead of showing a 404 page not found error, you create a new URL with updated business logic, and whenever a user accesses the old URL, Django will take the user to the new URL instead of displaying an error.

For example, if your old URL was something like example.com/old-way-to-contact-me/ and a client accesses the URL, Django should redirect them to a new page with a URL like example.com/new-way-to-contact-me/. The redirect happens automatically without the client realizing they are taken to a new URL. 

Here’s an example.

Let’s say the old URL is /contact-me in the urls.py

from django.urls import path

from .views import contact_me_view

urlpatterns = [
    path('contact-me', contact_me_view)
]

The contact_me_view would look like this in your views.py:

from django.shortcuts import redirect

def contact_me_view(request):
    template_name = 'contact.html'
    context = {
        'form': 'Contact form',
    }
    ...
    return render(request, template_name, context)

So, if you want to create a new view that returns a new contact page, you need to use the redirect() function to take a user to the new URL; let’s say /new-contact-me

So, you would replace the contact_me_view with the following code:

from django.shortcuts import redirect

def contact_me_view(request):
    return redirect('/new-contact-me')

Then create the new /new-contact-me URL

from django.urls import path

from .views import contact_me_view

urlpatterns = [
    path('contact-me', contact_me_view),
    path('new-contact-me', new_contact_me_view)
]

When users access the old URL, they will be redirected to a new URL with the updated business logic processing.

Next, let’s look at the HttpResponseRedirect() subclass.

What is HttpResponseRedirect() in Django?

Django HttpResponseRedirect is a subclass of the HttpResponse.

HttpReponseRedirect is used to return HTTP 302 status code that indicates that the URL resource was found but temporarily moved to a different URL. By providing a 302 OK status, HttpResponseRedirect() allows the client to access a temporary URL that the user can use to send requests and receive a response processed using a new view.

The requests are made using the new URL route with a new view that responds with a HttpResponse object.

The Django HttpReponse returns valid data when a valid request is made to a URL. The request passes through a view that processes the requests and provides a response.

Therefore, a temporary URL and page must exist for HttpResponse to work. More information about Django HttpResponse is in this article.

What is the difference between redirect and HttpResponseRedirect in Django?

While Django redirect reroutes a user accessing an old URL to a new URL, the HttpReponseRedirect provides a valid HTTP response to a client using a different URL.

A redirect() function takes a user to a new URL route whenever a user accesses an old URL. Therefore, the user makes requests using a new view.

On the other hand, the HttpResponseRedirect takes users to a different URL once they access a non-valid URL.

For example, suppose a user accesses a contact page and submits data. In that case, you may use HttpResponseRedirect to take the user to a different page that shows that the data was sent successfully by the form.

What is render() in Django?

The most important Django function in creating web pages is the render() function.

The render() function takes a template (HTML file) with a given context dictionary and returns a response as a HttpResponse object that has the text rendered.

If you have read about my HttpResponse article, you should have realized that a HttpResponse object is the data in the form of text such as HTML returned to a client upon requesting a server for a page by accessing a certain URL.

The render() function goes an extra mile by formatting the HttpResponse object.

The HTML text is formatted with the appropriate CSS styling.

Moreover, the render() function renders dynamic variables used to fetch data from the database or a form and use it in your template.

You request a page on a Django website, and the render function returns dynamic and formatted data instead of plain text.

The context dictionary contains dynamic data used with the template. For example, Django can fetch data from the database, such as all articles or a form, and that data can be used in your template dynamically.

Here is an example of a render function that renders an HTML template and context dictionary containing a form. The variable ‘form’ can be used in the template to display the text ‘Contact form’ on a rendered page.

from django.shortcuts import render

def contact_me_view(request):
    template_name = 'contact.html'
    context = {
        'form': 'Contact form',
    }
    ...
    return render(request, template_name, context)

What is the difference between render() and redirect() in Django?

The main difference between the render() and redirect() function is that the render() function returns a rendered text in the form of a HttpResponse object. In contrast, the redirect() function sends a user’s request to another URL different from the URL that made the request. 

The render() function combines the template with a context dictionary that contains data such as a form to be used in the template. The redirect() function takes a user accessing an old non-existing URL to a new valid URL.

And that’s it for this article.

I hope you understand how navigation and web page creation works in Django.

Share your love
Badi
Badi

Badi here, creator of ngangasn.com— A website dedicated to providing helpful information and how-to's of web development and hosting. Inspired by a fascination to write the most efficient code to make a computer laugh, & humans, Steve has a passion for organizing characters to create code and informative content.
What makes me happy?
Well, nothing like the feeling of finally figuring out that one pesky bug that's been driving me crazy.

Leave a Reply

Your email address will not be published. Required fields are marked *