URL Shortener Using Python Django

Introduction:
Long URLs can be shortened into short, shareable links with the help of the URL Shortener project. Though it was developed entirely with Django and Python, it shares a concept with Bitly and TinyURL.
When users enter a lengthy URL into a form, the backend uses hashing algorithms or random strings to create a unique slug. When accessed, this shortened URL then reroutes to the original link.
Along with analytics like click count, user IP, and access date, Django models save both the original and shortened links. Shortcut links and their statistics are shown on a dashboard. The problem of lengthy, unreadable URLs—which are prevalent in print, social media, and marketing materials—is resolved by this app. It’s helpful for monitoring user engagement as well.
With a list of generated URLs and a central input form, the interface is simple and elegant. Custom slugs, expiration dates, and dashboards tailored to each user are examples of enhancements.
The use of Django to mimic an actual SaaS product is what makes it unique. It’s great for teaching basic analytics, redirection logic, and slug fields.
Required Modules or Packages:
Python 3.8+: Make sure you have Python version 3.8 or higher installed on your system.
Django 3.x or 4.x: You’ll need the Django framework, version 3.x or 4.x, to build and run the system.
pip: This is the Python package manager that you’ll use to install the required libraries and packages.
You can install the core requirements with:
pip install django
pip install -r requirements.txt
How to Run the Code:
Follow these steps to launch the application locally:
✅ STEP 1: Download or Clone the Project
Option A: If you have a ZIP file
1. Extract it to a folder.
2. Open that folder in VS Code:
VS Code → File → Open Folder…
Option B: If using Git clone
git clone https://github.com/username/repository-name.git
cd repository-name
code .
✅ STEP 2: Set Up Virtual Environment
This keeps your project dependencies isolated.
# Create virtual environment (in project folder)
python -m venv venv
# Activate it:
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
✅ STEP 3: Install Requirements
Most Django projects have a requirements.txt file. Install the packages:
pip install -r requirements.txt
If requirements.txt is missing, you can manually install Django:
pip install django
✅ STEP 4: Configure .env or Settings (If Required)
Some projects require .env files (for secret keys or DB settings).
Check the README or .env.example if present, and create your own .env.
✅ STEP 5: Run Migrations
python manage.py makemigrations
python manage.py migrate
✅ STEP 6: Create Superuser (for Admin Login)
python manage.py createsuperuser
Follow the prompts.
✅ STEP 7: Run the Django Development Server
python manage.py runserver
Open http://127.0.0.1:8000 in your browser.
Use /admin to access the admin panel.
Code Explanation:
📁 1. Model: models.py
from django.db import models
class Shortener(models.Model):
full_url = models.URLField()
short_url = models.CharField(max_length=10, unique=True)
def _str_(self):
return self.full_url
full_url: Stores the original long URL.
short_url: A unique identifier (e.g., “a1b2c3”) used to redirect to the original URL.
_str_ makes it easy to display full URLs in the admin interface.
🧠 2. View Logic: views.py
import random, string
from django.shortcuts import render, redirect, get_object_or_404
from .models import Shortener
from .forms import UrlForm
def generate_short_url():
return ''.join(random.choices(string.ascii_letters + string.digits, k=6))
generate_short_url(): Creates a 6-character alphanumeric code.
This code will be the unique short path for the original URL.
🌐 Main View – Create Short Link
def home(request):
if request.method == 'POST':
form = UrlForm(request.POST)
if form.is_valid():
full_url = form.cleaned_data['full_url']
short_url = generate_short_url()
while Shortener.objects.filter(short_url=short_url).exists():
short_url = generate_short_url()
Shortener.objects.create(full_url=full_url, short_url=short_url)
return render(request, 'url_app/success.html', {'short_url': short_url})
else:
form = UrlForm()
return render(request, 'url_app/index.html', {'form': form})
Handles both GET and POST requests.
On form submission, it generates a unique short URL.
Ensures no duplicate short codes via a while loop.
Saves the mapping and returns the success.html with the shortened link.
🔁 Redirect View
def redirect_url(request, short_url):
link = get_object_or_404(Shortener, short_url=short_url)
return redirect(link.full_url)
Looks up the original URL via the short code.
Redirects the user to the correct full URL.
Uses get_object_or_404 to handle non-existent codes gracefully.
📝 3. Form: forms.py
from django import forms
class UrlForm(forms.Form):
full_url = forms.URLField(label='Enter the URL to shorten')
Simple form that takes a single input: the long URL.
🗺 4. URLs: urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('<str:short_url>', views.redirect_url, name='redirect')
]
Root URL (/) displays the form.
Shortened URLs like /abc123 are handled and redirected appropriately.
🎨 5. Templates
index.html: Displays the form for entering the full URL.
success.html: Shows the shortened link after generation.
Source Code:
To explore the full source code, click the button below to download the ZIP file and run it on your local machine:
Output:
