Django URL Shortener Project

In this “Django URL Shortener Project”, let’s discuss how we can create a website that shortens the URL. The functionality will be something similar to .

Installing Python

As Django is a Python-based web framework, we need to install Python first. You can download the Python version of your choice. In this project, I am using Python version 3.11.1

You can run the below command to check the Python version. If it shows the version correctly, it means Python is set up properly and we can move on to the next step.

C:\D_Drive\Github\tools>python --version
Python 3.11.1

Installing Django

Let’s use pip to install django. Here is the command that we can run:

pip install django

As you can see in this screenshot, I have already installed Django. If you are installing Django for the first time, you should see installation progress and then a completion message. As we have Python and Django set up correctly, we can move on to the next step.

Creating a Django Project and a Django App

Let’s create a Django project in the directory of your choice. We can use the django-admin command to create a project.

django-admin startproject url_shortener_proj

It should create a project directory called “url_shortener_proj”. We can now move inside this project directory, and create an app. Here is the command to do it:

cd url_shortener
django-admin startapp url_shortener

Defining the database model

Edit url_shortener/ file, define a model for storing the URLs and their shortened versions:

from django.db import models

class URL(models.Model):
    original_url = models.URLField()
    short_code = models.CharField(max_length=20, unique=True)
    creation_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.original_url

Edit url_shortener/ and add the following code:

from django.shortcuts import render, redirect
from django.http import Http404
from .models import URL
import random
import string

def index(request):
    if request.method == 'POST':
        original_url = request.POST['original_url']
        short_code = generate_short_code()
        URL.objects.create(original_url=original_url, short_code=short_code)
        return render(request, 'url_shortener/index.html', {'shortened_url': request.build_absolute_uri('/') + short_code})
    return render(request, 'url_shortener/index.html')

def redirect_original(request, short_code):
        url = URL.objects.get(short_code=short_code)
        return redirect(url.original_url)
    except URL.DoesNotExist:
        raise Http404("URL does not exist")

def generate_short_code():
    characters = string.ascii_letters + string.digits
    short_code = ''.join(random.choice(characters) for _ in range(6))
    return short_code

Create Django Templates

Edit url_shortener/templates/url_shortener/index.html and add the below code:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>URL Shortener</title>
    <h1>URL Shortener</h1>
    <form method="POST" action="{% url 'index' %}">
        {% csrf_token %}
        <input type="text" name="original_url" placeholder="Enter URL" required>
        <button type="submit">Shorten URL</button>
    {% if shortened_url %}
        <p>Shortened URL: <a href="{{ shortened_url }}">{{ shortened_url }}</a></p>
    {% endif %}

Configure URLs

Edit url_shortener/ and add the below code in that. The purpose of the code is to allow our website’s home page to be redirected to the index page (index.html) which we have created in the previous steps.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<str:short_code>/', views.redirect_original, name='redirect_original'),

Add the url_shortener app file

Update url_shortener_proj/, and add url_shortener in INSTALLED_APPS list.

    'url_shortener', # adding url shortener application in installed_apps

Updating url_shortener_proj/

Now, we want to tell Django to look for our applications’s file whenever user hits any URL. So we have to update url_shortener_proj/ with the below code.

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

urlpatterns = [
    path('', include('url_shortener.urls')),

Running Migrations

We will need to run migrations, which are going to create required databases and tables automatically based on the model we defined in url_shortener/

python makemigrations
python migrate

Run Django Server

python runserver

You should now see your application being served at location.

Sample output

PS C:\D_Drive\Github\tools\url_shortener_proj> python makemigrations
Migrations for 'url_shortener':
    - Create model URL

PS C:\D_Drive\Github\tools\url_shortener_proj> python migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, url_shortener
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK
  Applying url_shortener.0001_initial... OK

PS C:\D_Drive\Github\tools\url_shortener_proj> python runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
May 01, 2024 - 11:46:20
Django version 5.0.3, using settings 'url_shortener_proj.settings'
Starting development server at
Quit the server with CTRL-BREAK.

Launching the Website:

We can open the website now by typing the in the browser’s address bar. It displays a page as shown in this image.

Let’s provide a URL and click on “Shorten URL”. It should now generate a short URL as shown in the screenshot. We can now click on the URL and it will redirect us to

Conclusion: Django URL Shortener Project

In this article, we created a fully functional URL shortener project using Django. Now, in our next article, we will work on to enhance this project further. Do not forget to leave your feedback about this project in the comments section. I will be personally reading all the comments and replying them.

Leave a Comment

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

Scroll to Top