Open In App

Build a URL Size Reduce App with Django

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

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.

URL shortener using Bitly API in Django
File Structure

Add the app to INSTALLED_APPS:

Open URL_Shortner/settings.py and add home to the INSTALLED_APPS list:

URL shortener using Bitly API in Django
Installed Apps

Set the templates directory in the URL_Shortner/settings.py file.

URL shortener using Bitly API in Django
Templates

Set 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.

Create HTML Templates for the Form and Display

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 shortener using Bitly API in Django
URL Size Reduce App Using Django

Next Article

Similar Reads