Open In App

How to build a URL Shortener with Django ?

Last Updated : 26 Nov, 2020
Like Article

Building a URL Shortener, Is one of the Best Beginner Project to Hone your Skills. In this article, we have shared the steps to build a URL shortener using Django Framework. To know more about Django visit – Django Tutorial


We need some things setup before we start with our project. We will be using Virtual Environment for our project.

pip install virtualenv
virtualenv urlShort
source urlShort/bin/activate

Above Command will create, activate virtual environment named urlShort.

Installing Important Packages

We need to Install some packages before hand,

pip install django

Starting With Our Project

First of all, We need to create our project by,

django-admin startproject urlShort
cd urlShort

Above Command, Creates A Django Project and then cd into that directory. After that, We also need to create an app inside of our project. App is sort of a container, where we will store our code. A project can have Multiple Apps and they can be interconnected

python startapp url

Above Command Creates an App named URL in our Project. Our File Structure Now will be —

├── url
│ ├──
│ ├──
│ ├──
│ ├── migrations
│ │ └──
│ ├──
│ ├──
│ └──
└── urlShort
 ├── __pycache__
 │ ├── __init__.cpython-37.pyc
 │ └── settings.cpython-37.pyc

Checking If all is Great…

You can check if all is working by just typing this in Command Line. But cd into the main folder, here urlShort.

python runserver

runserver will run a local server where our website will load. Move to url


Keep Your Console Window Open.

How to Build a URL Shortener Project?

Tighten your seat belts as we are starting to Code. First of all, we will play with is basically used to connect our database, api with our Frontend. Open and type

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello World")

Save it and open localhost and check if it changes.It does not change because we have not map it to any route.Basically, If you write any function inside it does not work but we need to map it inside So, Create a inside url folder.

from django.urls import path
from . import views
app_name = "url"
urlpatterns = [
    path("", views.index, name="home")

Don’t forget to add your app – “urlin INSTALLED_APPS in

Creating Django Models –

First of all, we need a Database to store our Shorten URL’s. For That, We need to create a Schema for our Database Table in

from django.db import models
class UrlData(models.Model):
    url = models.CharField(max_length=200)
    slug = models.CharField(max_length=15)
def __str__(self):
        return f"Short Url for: {self.url} is {self.slug}"

Above Code Creates a Table UrlData in our Database with Columns url, slug. We will use url column to store Original URL and slug to store 10-character string which will be used for shortening the URL.

For Example,

Original URL —
Shorten Form — https://localhost:8000/sEqlKdsIUL

URL’s maximum length is 200 Characters and Slug’s maximum length is 15 (Considering our Website’s Address). After Creating Models for our Website, Let’s create some Forms for taking input from User. 

Creating a Form

Create a in our Django App Folder.

from django import forms
class Url(forms.Form):
    url = forms.CharField(label="URL")

We simply import forms from django and create a Class Url which we will use in and render it in our HTML. Url form has only a url field to take input of Original URL.

Creating Views

Now, We will create the Interface of our App using Let’s divide this part in Functions.

urlShort()— This Function is where our Main Algorithm works. It takes a url from form after User submits it, then it generates a Random Slug which is then stored in Database with Original Url. It is also the function which render index.html (entrypoint of our app) urlShort()

def urlShort(request):
    if request.method == 'POST':
        form = Url(request.POST)
        if form.is_valid():
            slug = ''.join(random.choice(string.ascii_letters)
                           for x in range(10))
            url = form.cleaned_data["url"]
            new_url = UrlData(url=url, slug=slug)
            return redirect('/')
        form = Url()
    data = UrlData.objects.all()
    context = {
        'form': form,
        'data': data
    return render(request, 'index.html', context)

urlRedirect() — This Function tracks the slug to Original URL and redirects it to Original URL. urlRedirect()

def urlRedirect(request, slugs):
    data = UrlData.objects.get(slug=slugs)
    return redirect(data.url)

Creating Routes 

Before Running This App, We need to specify URL paths in App’s

from django.urls import path
from . import views
app_name = "url"
urlpatterns = [
    path("", views.urlShort, name="home"),
    path("u/<str:slugs>", views.urlRedirect, name="redirect")

Run the Project

Open Console in Main Project Directory.

python runserver

Final Project Output – 

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads