Redirect in Django

Redirect in Django

Django is such an amazing framework! Everything built-in is for a reason and every time fascinates users to do even more and use a compact approach. You won’t believe redirecting is damn easy in Django. You can do it using a single word. You heard it right! A single word, not even a line or plenty of code.

This tutorial will let us know how to redirect in Django.

Why redirecting?

The question is why we actually need to redirect. Let’s talk about a task when you need to display or show another page or URL in a project. For example, after login, you need to redirect the user to the dashboard, or if you are at Codespeedy you could see posts in a compact view which would be later opened on clicking a particular post. These are some examples and needs why do we need to redirect a user to some other place.

So here we have understood the need for redirecting. We would now try to redirect using some of the methods mentioned in the official Django repo.

Here’s the link to the official repo¬†https://docs.djangoproject.com/en/4.0/topics/http/shortcuts/

After visiting this URL you might have got the idea regarding redirection in Django.

To redirect to an object of a model in Django

Let’s try to implement this-

Start your project and your app.

Your models.py should include-

from django.db import models

# Create your models here.
class Details(models.Model):
    name=models.CharField(max_length=45)
    desc=models.TextField()
    dob=models.DateField()

    def __str__(self):
        return self.name
    def get_absolute_url(self):
        return "/details/%i" %self.id

This code is to create a model and then get URL for the objects.

Open your urls.py and write the below code-

from django.contrib import admin
from django.urls import path

from yourappname import views



urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home,name="home"),
    path("objects",views.objects,name="objects"),
    path("details/<str:pk>/",views.detail,name="detail"),
]

These are the URLs of the project.

Then you have to create views in your views.py inside your app.

from django.shortcuts import redirect, render
from yourappname.models import Details
# Create your views here.
def home(request):
    return render(request,"index.html")
def objects(request):
    detail=Details.objects.get(name="Codespeedy")
    return redirect(detail,permanent=True)


def detail(request,pk):
    detail=Details.objects.get(id=pk)
    print(detail)
    context={
        'detail':detail,
    }

    return render(request,"record.html",context)

You have to create a folder named templates, inside it create a file named index.html and detail.html

Code inside index.html-

<h1>Home Page</h1>
<a href="{% url 'objects' %}">Objects</a>

Code in detail.html-

{{detail}}<br>
{{detail.desc}}

You need to register your model in admin.py as-

from django.contrib import admin
from tutorial.models import Details
# Register your models here.
admin.site.register(Details)

At the end, you just need to include your app inside settings.py-

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yourappname',
]

Create a superuser and then login to Django Administration using the credentials after the next step.

Make migrations and migrate the changes.

Run the server.

You will be able to see screen like-

Redirect in Django

Click on objects. You should be able to see-

redirect

So if you can see the above screen, we have successfully completed the task to redirect the user to some other place,i.e. objects using a query.

To redirect to any URL in Django

You might need to redirect to some particular URL.

Follow the above steps except for urls.py and views.py

Open your urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home,name="home"),
]

views.py

def home(request):
    return redirect("https://www.codespeedy.com/")

You will be redirected to the official site of codespeedy when you hit python manage.py runserver

I hope you enjoyed reading this tutorial and appreciate it too, feel free to comment and share your reviews.

Leave a Reply

Your email address will not be published.