How to Build a URL Shortener with Django
Last Updated :
13 May, 2025
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).
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
URL Shortener with Django
Similar Reads
How to build a URL Shortener with Django ?
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. SetupWe need some things setup before we start with our project. We will be using Virtual Environment for our project.pip i
5 min read
Build a URL Size Reduce App with Django
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this article, we will learn to build a URL shortener using Django. A URL shortener is used to reduce the size of long URLs. Short URLs are better for sharing purposes. In this article, we wi
5 min read
Python | How to shorten long URLs using Bitly API
Bitly is used to shorten, brand, share, or retrieve data from links programmatically. In this article, we'll see how to shorten URLs using Bitly API. Below is a working example to shorten a URL using Bitly API. Step #1: Install Bitly API using git git clone https://github.com/bitly/bitly-api-python.
2 min read
How to Send Email with Django
Django, a high-level Python web framework, provides built-in functionality to send emails effortlessly. Whether you're notifying users about account activations, sending password reset links, or dispatching newsletters, Djangoâs robust email handling system offers a straightforward way to manage ema
4 min read
Get the Absolute URL with Domain in Django
When developing web applications, generating the full URL (including the domain) is often necessary. For instance, sending confirmation emails with links, generating sitemaps, or creating social media share links require absolute URLs. Django provides several utilities and methods to achieve this se
3 min read
Get the Current URL within a Django Template
Django, a high-level Python web framework, encourages rapid development and clean, pragmatic design. One common requirement when developing web applications is to access the current URL within a template. This can be useful for various purposes such as highlighting the active link in a navigation me
3 min read
How to Render Data in Django
Django's render() function is a fundamental tool for building dynamic web applications. It simplifies the process of combining HTTP requests with HTML templates and dynamic data, making it easier for developers to create interactive and data-driven web pages. What is render()?In Django, the render(
3 min read
Building APIs using FastAPI with Django
Combining FastAPI and Django can leverage the strengths of both frameworks: FastAPI's high performance for building APIs and Django's powerful ORM and admin interface. In this guide, we'll outline how to integrate FastAPI into a Django project to build high-performance APIs.In this article, we will
2 min read
Django REST API - CRUD with DRF
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around the Django Framework. There are three stages before creating an API through the REST framework, Converting a Modelâs data to JSON/XML format (Serialization), Rendering this data to the view, and Cr
7 min read
How To Integrate Ajax with Django Applications
Django is one of the most popular web frameworks for building robust and scalable web applications. However, many modern applications require asynchronous features, enabling real-time interactions without the need to reload the entire page. This is where Ajax (Asynchronous JavaScript and XML) comes
5 min read