Build a URL Size Reduce App with Django
Last Updated :
21 May, 2025
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-to-follow way.
Setup a New Django Project
Prerequisites:
Open your terminal and run the following command to create a new Django project:
django-admin startproject URL_Shortner
cd URL_Shortner
Create an app named home where the logic for the URL shortener will be handled.
python manage.py startapp home
This is the final file structure after completing the project.
File StructureAdd the app to INSTALLED_APPS:
Open URL_Shortner/settings.py and add home to the INSTALLED_APPS list:
Installed AppsSet the templates directory in the URL_Shortner/settings.py file.
TemplatesSet Up URLs for the Project and App
1. Update the project’s urls.py:
Open URL_Shortner/urls.py and configure it to include URLs from the home app.
Python
from django.contrib import admin
from django.urls import path, include
import home
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(home.urls)),
]
2. Set up URLs in the home app:
In home/urls.py, set up the routes for the home page and form submission.
Python
from django.urls import path
from home import views
urlpatterns = [
path('',views.index),
path('index_form',views.index_form),
]
Create the Views to Handle User Requests
Create the views:
In home/views.py, create functions to handle the form display and URL shortening process using the Bitly API.
Python
from django.shortcuts import render, redirect
import requests
BITLY_ACCESS_TOKEN = 'your_bitly_access_token' # Replace with your Bitly token
def index(request):
return render(request, 'index.html')
def index_form(request):
if request.method == 'POST':
long_url = request.POST.get('long_url')
shortened_url = shorten_url(long_url)
return render(request, 'new_url.html', {'shortened_url': shortened_url})
return redirect('index')
def shorten_url(long_url):
url = 'https://api-ssl.bitly.com/v4/shorten'
headers = {
'Authorization': f'Bearer {BITLY_ACCESS_TOKEN}',
}
data = {'long_url': long_url}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json()['link']
else:
return 'Error shortening URL'
Explanation:
- index() renders the homepage where users enter the URL.
- index_form() handles the form submission, calls the shorten_url() function, and renders the shortened URL.
- shorten_url() interacts with the Bitly API to shorten the given URL.
1. Set up the templates folder:
Create a templates directory inside the home app. Inside this directory, create the index.html and new_url.html files.
2. Create index.html:
This file displays the form where users can input a long URL.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Baloo+Chettan+2:wght@700&display=swap" rel="stylesheet">
<style>
body{
background-color: rgb(171, 240, 254);
}
.selfhead{
font-size: 90px;
font-weight: bolder;
font-family: 'Baloo Chettan 2', cursive;
}
@media only screen and (max-width:485px){
.selfhead{
font-size: 50px;
font-weight: bold;
}
}
</style>
<title>GFG</title>
</head>
<body>
<div class="container" id="Contact-us">
<div class="selfhead text-center py-0 ">
URL shortener
</div>
</div>
<div class="container my-3">
<form method="post" action="/index_form">
{%csrf_token%}
<div class="mb-3">
<label for="url" class="form-label fw-bold">Enter Long URL</label>
<input type="text" class="form-control" id="url" aria-describedby="emailHelp" placeholder="Enter your URL" name="long_url">
</div>
<p class="text-center"><button type="submit" class="btn btn-danger">Submit</button>
</p>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
3. Create new_url.html:
This file will display the shortened URL after processing.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Baloo+Chettan+2:wght@700&display=swap" rel="stylesheet">
<style>
body{
background-color: rgb(171, 240, 254);
}
.selfhead{
font-size: 90px;
font-weight: bolder;
font-family: 'Baloo Chettan 2', cursive;
}
@media only screen and (max-width:485px){
.selfhead{
font-size: 50px;
font-weight: bold;
}
}
</style>
<title>GFG</title>
</head>
<body>
<div class="container" id="Contact-us">
<div class="selfhead text-center py-0 ">
URL shortener
</div>
</div>
<div class="container my-3">
<form method="post" action="/index_form">
{%csrf_token%}
<div class="mb-3">
<label for="url" class="form-label fw-bold">Enter Long URL</label>
<input type="text" class="form-control" id="url" aria-describedby="emailHelp" placeholder="Enter your URL" name="long_url">
</div>
<p class="text-center"><button type="submit" class="btn btn-danger">Submit</button>
</p>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
Use the Bitly API Access Token
1. Generate an Access Token on Bitly:
- Visit "https://bitly.com/" and create an account if you haven't already.
- Go to Settings > API and generate an Access Token.
2. Use the Access Token:
- In home/views.py, set the BITLY_ACCESS_TOKEN to the token you generated.
- This will allow the app to authenticate with Bitly’s API to shorten the URLs.
Test the Application
1. Run the Django development server:
python manage.py runserver
2. Visit the app:
Open your browser and go to http://127.0.0.1:8000/ to view the homepage.
3. Submit a URL:
Enter a long URL in the form, and the app will redirect to the new_url.html page with the shortened URL.
Output:
On submitting the URL a new page appears with a new short link.
URL Size Reduce App Using 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
Building Web App with Django and FastAPI Django is a powerful and popular web framework for building robust web applications with Python. It comes with a lot of built-in features, including an ORM, an authentication system, and a powerful admin interface. However, there are scenarios where you might want to integrate Django with FastAPI, a
4 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
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