A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/build-a-url-size-reduce-app-with-django/ below:

Build a URL Size Reduce App with Django

Build a URL Size Reduce App with Django

Last Updated : 23 Jul, 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 Structure Add the app to INSTALLED_APPS:

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

Installed Apps

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

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:

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/bootstrap@5.2.2/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/bootstrap@5.2.2/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/bootstrap@5.2.2/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/bootstrap@5.2.2/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: 2. Use the Access Token: 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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4