Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django Redirects – How to Add a Redirect to Your Django Page?

Django Redirect

In this article, we will learn about Django redirects using the Django Http library. We’ll briefly talk about the use cases and the applications of the redirect method.

Why do we need redirection in Django?

Redirection to another site is an essential part of the web application. It enhances the efficiency of the web pages.

  • Let us take an example of Facebook, if you are not already logged in, then as soon as you hit the FB URL, you are redirected to the log-in Authentication Site. This is where redirect comes into play.
  • Similarly, once the payment is confirmed, you are redirected to the confirmation page when you do an online transaction.
  • Another benefit of redirect is that it helps in URL shortening—for example, https://bit.ly. Here you type a short URL and are then redirected to the original long one. 

Hence Redirect places a vital role in web development. Now that we know what redirect is used for let’s dive right into it !!

The Django redirect() Function 

A webpage can be redirected using the redirect() function in 3 ways:

  1. Using Views as it’s arguments
  2. Using URLs directly as arguments

We will now see each of them in detail.

Let’s create a webpage that requires a Model Table to store articles and function Views to link them up.

Prerequisites for handling redirect()

There are a few underlying pieces of code that you’d need to create your first redirect. I’m adding the basic requirements here.

1. Build the Django Model

Create a model ArticleModel and add the following fields

class ArticleModel(models.Model):
    author = models.CharField(max_length = 80)
    article_title = models.CharField(max_length = 80)
    article = models.TextField()

    class Meta:
        ordering = [ 'article_title']

    def __str__(self):
        return f"{self.article_title} by {self.author}"

Run the migrations to create a table in the DB.

python manage.py migrate
python manage.py makemigrations

Let us also add a few objects into the ArticleModel DB,

Article Model
Article Model

2. Create a Django View

Create a ArticleView and add the following code:

def ArticleView(request,title):
    article = ArticleModel.objects.get(article_title = title)
    return HttpResponse(article)

Here, the view displays the article searched by the user. The URL path for this View:

path('article/<article_name>', ArticleView, name=ArticleView),

3. Code the Search Form

We will require a search form through which the user can be redirected to a particular article.

Don’t Worry if you are not familiar with forms, just copy paste the below code into a forms.py file in your project.

class ArticleForm(forms.Form):
    title = forms.CharField(max_length =80)

If you wish, you can check out the Django Forms article

4. Make the Templates for Display

Here we will use a template to display the SearchForm.

Don’t worry if you are not familiar with Forms or Templates, just add the following HTML code in the templates folder.

<form method ='post'>
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value = "Submit">
</form>

That’s it, let us now go back to code the redirect() function.

Adding the Django redirect() Method

Let’s get right into building our first Django redirect with the redirect method here.

1. Using a View as argument

In this case, the syntax for Django redirect() method is as shown:

redirect('<view_name>',<view_arguments>)

We will use the Search Form through which a user will be redirected to the article webpage.

Now add the following view into views.py

from django.shortcuts import redirect

def SearchView(request):

    if request.method == 'POST':
        form = ArticleForm(request.POST)

        if form.is_valid():
            title = form.cleaned_data['title']
            return redirect('ArticleView', title = title)
        
    else:
        form = ArticleForm()
        context ={
            'form':form,
        }
    return render(request, '<app_name>/Form.html(path to the template)', context)

Here we are re-directing this View to the above ArticleView. The URL path for this view:

path('articles/search', SearchView)

2. Using direct URLs as arguments

In this case, the syntax for redirect() is as shown:

redirect('URL')

Add the following View into views.py. Let us redirect this View to, let say askpython home page.

def URLView(request):
    return redirect('https://wwww.askpython.com')

The URL path for this view:

path('redirect/', URLView)

That’s it; the coding part is done. Let us now implement it.

Implementing the Views

Fire up the server, and go to “articles/search/”

Search Form
Search Form

Hit submit and the browser will be redirected to ArticleView

Article View
Article View

Now we will run the 2nd code.

Enter “127.0.0.1:8000/redirect/” on your local browser, and hit enter. You will be redirected to the AskPython site

Ask python
Ask python

See how efficient the webpage becomes with the redirect() function.

Conclusion

That’s it, guys!

As a practice, you can try to use Django redirects as URL shorteners. Do give it a shot.

Hope you guys had a good understanding of Django redirects and how you can use them to make your websites faster and more efficient. Keep practicing!