Django Redirect

Learn via video courses
Topics Covered

Overview

The user will probably need to be redirected from one URL to another when you create web apps in Python using the Django framework. The information you require for redirecting in Django through django redirect is covered in this tutorial.

What are Redirects?

When building a web application with Django, we will sometimes need to navigate from one URL to the other. By returning an instance of HttpResponseRedirect from views.py/ function in view.py in Django, we can quickly switch from the current URL to another URL. In our view.py, (to use django redirect) redirect is imported from the django.shortcuts module.

For reference, we'll see an example:

Simply pass a URL from your view to redirect(). You then return the returned HttpResponseRedirect class from the view.py. You must include a view function/method returning a redirect in your urls.py file.

Django redirect URL or URL /redirect/ now points to /redirect-success/ if this is the main urls.py file for your Django project. You can call redirect() using the name of a view, a URL pattern, or a model instead of hard-coding the URL to avoid doing this.

Why Redirect?

One may wonder why one would ever want to send a user to a different URL in the first place. Look at how Django itself includes django redirects into the capabilities that the framework offers by default to get a notion of when they make sense:

  • Django takes you to the login page when you attempt to access a django redirect URL that needs authentication while you are not logged in, such as the Django admin.
  • Django directs you to the original URL you requested when you successfully log in.
  • You are routed to a screen that states that the password change was successful when you modify it using the Django admin.
  • Django takes you to the object list once you create an object in the Django admin.

Django redirects is crucial in helping the web application give the user direction. Applications may experience some annoyance as a result of activities like generating or deleting objects. Redirect can be used to avoid accidentally operating twice.

Temporary Redirects vs Permanent Redirects

The HTTP standard lists a number of redirect status codes, all of which fall within the 3xx range. The 301 Permanent Redirect and 302 Found status codes are the most often used ones.

A Temporary redirect is indicated by the status code 302 Found. A temporary redirect adds, "At the moment, the thing you're seeking can be found at this other address."

Permanent redirects are intended to be the thing you're looking for that is no longer at this address. It has moved to this new address and won't ever return to the previous one. This change is permanent, so you should head straight to the new address the next time you need to visit the store because our new location is just around the corner. When handling redirects, browsers act similarly: a URL's response to a permanent redirect is cached. The browser will remember the redirect and use the new address directly the next time it encounters the old URL.

HTTPResponseRedirect

The HttpResponseRedirect, a subclass of HttpResponse, can help you type less. The class will automatically set the proper status and Location header if you simply instantiate it with the URL you wish to redirect to as the first argument.

Additionally, a class called HttpResponsePermanentRedirect exists specifically for permanent redirects. The only difference between it and HttpResponseRedirect is that it has a status code of 301 (Moved Permanently).

Introduction to redirect() Function

Django offers the flexible shortcut method you previously saw in the introduction to help make your life easier which is (django redirects) django.shortcuts.redirect(). This function can be used with:

  • Any object has the get_absolute_url() method, such as a model instance.
  • Positional and/or keyword arguments, a URL or view name
  • A django redirect URL/URL

The right steps will be taken to convert the arguments into a URL, and it will provide back an HTTPResponseRedirect. A permanent django redirect will occur if you specify the parameter permanent=True, which causes it to return an instance of HttpResponsePermanentRedirect. Some different use cases concerning the redirect() function:

1. Passing a model:

ExampleModel will be called by redirect(). Use the output of get_absolute_url() as the target for a redirect. This will fail with a TypeError if the specified class, in this example, does not have a get absolute url() method.

2. Passing a URL name and arguments:

Redirect() will attempt to reverse a URL using the arguments provided.

3. Passing a URL:

Any string that contains a / or . is treated as a URL by redirect() and is used as the redirect target.

Basic Example

Redirecting a user to another URL after successfully submitting a form is one example of how redirects are used in this context. An example of code that shows how to handle a form is shown below:

This view's function is to show and manage a form that lets users send messages. Let's proceed in this manner:

  • The view first examines the request method. The browser sends a GET request when a user accesses the URL linked to this view.
  • The POST data is utilized to create a ContactForm object if the view is called with a POST request.
  • The form data is supplied to send a message if the form is valid(). This function is not displayed here since it is not applicable in the given situation.
  • The view produces a redirect to the URL /success/ after the message has been sent. Our focus is on this particular stage. The URL is hard-coded in this instance for simplicity. We'll cover how to prevent that later.
  • A ExampleForm instance is created and the example_form.html template is rendered using django.shortcuts.render() if the view receives a GET request (or, more precisely, any request that is not a POST request).

Only the /success/ URL is loaded if the user clicks the reload button at this point. Reloading the page would force a second submission of the form and another message if there was no redirect.

The RedirectView Class-Based View

You could implement the class-based view if your view only ever returns a redirect by using django.views.generic.base.RedirectView. RedirectView has many features you may use to customize it to your requirements. A django redirect URL will be used if the class has the .url attribute. Named arguments from the URL are used in place of string formatting placeholders:

The URL has a term definition that will aid in redirect construction. If we type "XYZ" name into Google, the result will be here. To view(), we pass the keyword parameter url in the urlpatterns.

Through overwriting the get_redirect_url() method, we can construct the dynamic URL.

The class-based view mentioned above redirects to a URL chosen at random from .example_urls.

django.views.generic.base.RedirectView provides a few extra customization hooks. The full list is provided below:

  • .url: A string containing a URL to redirect to should be present if this property is set. %(name)s and other string formatting placeholders are extended using the keyword arguments sent to the view if they are present.
  • .pattern_name: It should be the name of a URL pattern to redirect to if this property is set. The view uses any positional and keyword arguments supplied to it to reverse the URL structure.
  • .permanent: A constant redirect is returned by the view if this property is set to True. False by default.
  • .query_string: Any specified query string is added by the view to the redirect URL if this property is set to True. The query string is ignored if the value, which is the default, is False.
  • get_redirect_url( * args, ** kwargs): The django redirect URL is created using this way. The view returns 410 Gone status if this method returns None.

The default implementation looks up the .url file first. It uses any named URL parameters supplied to the view to extend any named format specifiers, treating .url as an "old-style" format string. If .url is not set, .pattern_name is checked instead. If it is, it utilizes it along with any positional and keyword arguments it was given to reverse a URL. By overwriting this method, you can alter that behavior in any way you choose. Just make sure a string containing a URL is returned.

Advanced Usage

Once you are aware that django.shortcuts.redirect() is what you should most likely use, redirecting to a different URL is a simple process. However, there are a few less obvious advanced application cases.

Passing Parameters with Redirects

You may sometimes have to add some extra information to the view you're redirecting to. The best course of action is to transmit the information in your redirect URL's query string, which calls for rerouting to a URL like this:

Example:

Let's understand the above code, step by step:

  1. The URL mapping to the product view is first obtained using django.urls.reverse().
  2. Now you must use a question mark to link the base URL and query string. For that, a format string is adequate.
  3. A django redirect response class or django.shortcuts.redirect() is where you supply the URL to complete the process.
  4. The parameter will be accessible in the request.GET dictionary in product view(), the function that will handle your reroute. You should use requests because the argument might not be present. instead of requests.GET.get("firstName"), use requests.GET['firstName']. While the latter would throw an exception, the former returns None when the parameter is null.

Special Redirect Codes

The status codes 301 and 302 are covered by HTTP response classes that Django offers. Although those should cover the majority of use cases, you may fairly easily develop your response class if you ever need to return status codes 303, 307, or 308.

To build a response object and modify the return result, you may also use the django.shortcuts.redirect() method. This method is appropriate when you know the name of a view, URL, or model to which you wish to redirect:

Redirect Loop

When working with django redirects or django redirect url , you run the risk of unintentionally creating a redirect loop if URL A produces a redirect that goes to URL B, which then returns a redirect to URL A, and so on. The majority of HTTP clients are capable of spotting this form of redirect loop and, after a few requests, will indicate an error.

On the server side, everything appears to be working well, therefore this kind of error can be difficult to detect. The only sign that something might be wrong unless your users report it is when a single client makes several requests which all swiftly follow with a redirect response but no response with a 200 OK status.

Simple Example of a Redirect Loop

Although this example oversimplifies the concept, it does explain it. Real-world redirect loops will undoubtedly be more challenging to identify. Although there is no foolproof method to stop this kind of problem, it is a good place to start to see if the view you are diverting to uses redirects.

More Examples

Passing a Hardcoded URL to Redirect to

with full URLs

A Permanent Argument Set to True a Permanent Redirect will be Returned

Security Perspective

Redirects are a generally safe technique in terms of security. A django redirect prevents an attacker from hacking the website. After all, a redirect simply directs traffic to a URL that a hacker needs only type into their browser's address bar.

However, using user input, such as a URL parameter, as a django redirect URL without proper validation leaves room for abuse by an attacker to launch a phishing attack. Open or unvalidated redirects are what this type of redirect is known as.

There are valid reasons to redirect to a URL that was entered by the user. The login view in Django is a good illustration. The URL of the page to which the user is directed after logging in is accepted as the next URL parameter.

The parameter next is validated by Django, but let's pretend for a moment that it isn't. Without verification, a malicious party may create a URL that takes users to a website they control.

The user may then be tricked into entering their login information again by the website articlesBlog.com displaying an error message. Creating a django redirect URL without using any user input is the best way to prevent open redirects.

Conclusion

This concludes the tutorial on using Django to perform HTTP redirects. You now understand what a django redirect/redirect looks like on the inside, the meaning of the various status codes, and the distinctions between permanent and temporary redirects. Any language can be used to develop websites using this knowledge, which is not specific to Django.

Let's see the important points we learn from this tutorial:

  • Redirect function can perform by using the convenience function django.shortcuts.redirect or the redirect response classes HttpResponseRedirect and HttpResponsePermanentRedirect.
  • A permanent redirect will occur if you specify the parameter permanent=True, which causes it to return an instance of HttpResponsePermanentRedirect.
  • We can implement the redirect() in class-based view if your view only ever returns a redirect by using django.views.generic.base.RedirectView. RedirectView has many features you may use to customize it to your requirements.
  • A redirect prevents an attacker from hacking the website. After all, a redirect simply directs traffic to a URL that a hacker needs only type into their browser's address bar.