Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Build a URL Size Reduce App with Django
Next article icon

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

Next Article
Build a URL Size Reduce App with Django

S

sk1122
Improve
Article Tags :
  • Python
  • Django
  • Python Django
Practice Tags :
  • python

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
    We will build a simple Django app that shortens long URLs. Users will enter a URL on the homepage, submit it, and instantly get a shortened link on the next page. We’ll set up the Django project, connect to Bitly with an access token, handle user input, and display the results all in a clean, easy-t
    4 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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences