Open In App

How to Build a URL Shortener with Django

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Building a URL Shortener, Is one of the Best Beginner Project to sharpen your Skills. In this article, we have shared the steps to build a URL shortener using Django Framework.

Setup

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 manage.py startapp url

File Structure

Above Command Creates an App named URL in our Project. Our file structure now will be:

urlShort
├── manage.py
├── url
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── urlShort
├── asgi.py
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ └── settings.cpython-37.pyc
├── settings.py
├── urls.py
└── wsgi.py

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

python manage.py runserver

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

https://localhost:8000

Keep Your Console Window Open.

Project Overview

A URL shortener application will allow users to input long URLs and receive a shortened version of those URLs that can be shared easily. Building a URL shortener is a useful project for learning Django. If you're eager to develop more advanced Django apps, the Django Web Development Course is designed to help you tackle more complex projects.

Step 1: Creating the Models

In Django, models are used to define the structure of your database. For our URL shortener, we need to create a model to store both the original URL and the shortened URL (slug).

Open models.py in the url app and define the model like this:

Python
# url/models.py
from django.db import models

class UrlData(models.Model):
    url = models.CharField(max_length=200)  # Store the original URL
    slug = models.CharField(max_length=15)  # Store the shortened slug

    def __str__(self):
        return f"Short URL for: {self.url} is {self.slug}"

Explanation:

  • url: This field stores the original URL.
  • slug: This field stores the shortened version of the URL (a 10-character string).

Step 2: Creating the Forms

Next, we need to create a form that will allow users to input their URLs for shortening. To do this, create a forms.py file in your url app and define the form:

Python
# url/forms.py
from django import forms

class Url(forms.Form):
    url = forms.CharField(label="URL")  # Input field for the original URL

This form will be used in our views to get the user’s original URL and process it.

Step 3: Creating the Views

Now, we’ll define the views in views.py to handle the logic for URL shortening and redirection.

1. urlShort(): Handle URL Shortening

This function will take the original URL, generate a random 10-character slug, store both in the database, and return the shortened URL.

Python
# url/views.py
import random
import string
from django.shortcuts import render, redirect
from .models import UrlData
from .forms import Url

def urlShort(request):
    if request.method == 'POST':
        form = Url(request.POST)
        if form.is_valid():
            # Generate a random 10-character slug
            slug = ''.join(random.choice(string.ascii_letters) for _ in range(10))
            url = form.cleaned_data["url"]  # Get the original URL from the form
            new_url = UrlData(url=url, slug=slug)  # Save the URL and slug
            new_url.save()
            return redirect('/')  # Redirect to the homepage after saving
    else:
        form = Url()  # Empty form if it's a GET request

    data = UrlData.objects.all()  # Get all shortened URLs
    context = {
        'form': form,
        'data': data
    }
    return render(request, 'index.html', context)

2. urlRedirect(): Redirect to the Original URL

This function will take the slug from the URL and redirect the user to the corresponding original URL.

Python
# url/views.py
from django.shortcuts import redirect
from .models import UrlData

def urlRedirect(request, slugs):
    # Find the original URL by the slug
    data = UrlData.objects.get(slug=slugs)
    return redirect(data.url)  # Redirect to the original URL

Step 4: Creating the Templates

The next step is to create the HTML template that will display the URL shortening form and show the list of shortened URLs. Create a new file index.html inside url/templates:

HTML
<!-- url/templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>URL Shortener</title>
</head>
<body>
    <h1>Welcome to the URL Shortener</h1>

    <!-- Form to submit the original URL -->
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Shorten URL</button>
    </form>

    <h2>Shortened URLs</h2>
    <ul>
        {% for entry in data %}
            <li>{{ entry.url }} → <a href="/u/{{ entry.slug }}">/u/{{ entry.slug }}</a></li>
        {% endfor %}
    </ul>
</body>
</html>

This template contains:

  • A form to input the original URL.
  • A list of all previously shortened URLs, each linked to its corresponding shortened path.

Step 5: Creating URL Routes

To connect our views to specific URLs, we need to define URL routes in the urls.py file of the url app.

Python
# url/urls.py
from django.urls import path
from . import views

app_name = "url"

urlpatterns = [
    path("", views.urlShort, name="home"),  # Home route for URL shortening form
    path("u/<str:slugs>", views.urlRedirect, name="redirect"),  # Redirect using the slug
]

Explanation:

  • The first route ("") is for the home page where users can submit their URLs.
  • The second route ("u/<str:slugs>") is for redirecting users to the original URL based on the slug.

Step 6: Running the Project

Now that everything is set up, we can run the Django development server and test our URL shortener. In your project’s root directory, run the following command:

python manage.py runserver

Once the server is running, open a browser and go to:

http://localhost:8000/

Output

urlShortener
URL Shortener with Django

Article Tags :
Practice Tags :

Similar Reads