How to build a basic Django URL shortener

Django is a Python-based Model View Controller (MVC) web framework that allows us to build fast and efficient websites. Its decoupled architecture facilitates easy scalability, and its powerful caching framework significantly speeds up web application response times.

Flow of a Django application
Flow of a Django application

However, the MVC architecture in Django can be better called the Model View Template (MVT) architecture. In Django:

  • Models manage the data and database operations.

  • Views handle the application logic and act as controllers.

  • Templates render the HTML content and presentation.

Components in MVC vs. MVT

Purpose

Responsible Component in MVC

Responsible Component in MVT

Storing and maintaining data

Model

Model

Providing interactive endpoint to the user

View

Template

Processing and forwarding requests

Controller

View

Working with Django

While Django is a very popular framework and it's easy to jump right into creating a Django application, we should make sure we meet all of its prerequisites.

Prerequisites

In order to create any Django application, please ensure that we have:

  • Basic knowledge of Python

  • Python installed on the system

Installing Django

Begin by installing Django with the following command:

pip install django
Command to install Django

Django URL shortening application

A URL shortening application is a common app that takes a long URL and converts it into a shorter, more manageable link. Building a basic application with Django is a great way to learn web development with this powerful framework. Here’s a step-by-step guide to building it in Django:

The starting page of the application
The starting page of the application
1 of 3

Step 1: Set up the Django project

  1. Create a new Django project and application: Use the following terminal commands to create a Django project urlshortener and an application shortener within the project:

django-admin startproject urlshortener
cd urlshortener
python3 manage.py startapp shortener
Creating a Django project and application
  1. Add the application to the project's settings: Since the name of our application is shortener, go to the /usercode/urlshortener/urlshortener/settings.py file and add 'shortener' to the list of INSTALLED_APPS as follows:

INSTALLED_APPS = [
...
'shortener',
]
Adding application to the project

Note: The /usercode directory is the default workspace directory on the Educative platform to build your application.

  1. Define host names that your application is allowed to serve: Set ALLOWED_HOSTS = ['*'] in the /usercode/urlshortener/urlshortener/settings.py file to allow accepting requests from any domain or set ALLOWED_HOSTS = ['<specific_url>'] to restrict requests to a certain domain only.

Step 2: Define the URL model

  1. Create the URL model: In the /usercode/urlshortener/shortener/models.py file, define a simple model to store the input and respective shortened URLs in the database:

from django.db import models
import string
import random
class URL(models.Model):
# Fields for the original URL and the shortened code
original_url = models.URLField()
short_code = models.CharField(max_length=6, unique=True)
# Custom save method to ensure a short code is generated if not provided
def save(self, *args, **kwargs):
if not self.short_code:
self.short_code = self._create_unique_short_code() # Generate short code if not already set
super(URL, self).save(*args, **kwargs)
# Method to create a unique 6-character short code
def _create_unique_short_code(self):
characters = string.ascii_letters + string.digits
while True:
short_code = ''.join(random.choices(characters, k=6))
if not URL.objects.filter(short_code=short_code).exists():
break
return short_code
def __str__(self):
# Return the original URL when the instance is represented as a string
return self.original_url
Defining the URL model
  • In the above code, there's an integral function generate_short_code() that's responsible for generating shortened URLs against the provided URL. Here's the line-by-line breakdown:

    • Line 18: This defines characters as a combination of both letters and digits.

    • Line 20-21: This generates short_code using the random.choices() function from our defined set of characters for 6 characters. If the generated short_code already exists in the database, it outputs it; otherwise, it regenerates it to ensure uniqueness.

    • Line 22: This returns the unique short_code.

  1. Run migrations to create the database table: Run the following commands in the terminal to create the tables:

python3 manage.py makemigrations
python3 manage.py migrate
Create the model

Step 3: Create views

  1. Create views for URL shortening and redirection: In the /usercode/urlshortener/shortener/views.py file, define the views as follows:

from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from .models import URL
# View function to handle URL shortening
def shorten_url(request):
if request.method == 'POST':
original_url = request.POST['original_url'] # Get the original URL from POST data
url, created = URL.objects.get_or_create(original_url=original_url) # Get or create URL the object
short_url = request.build_absolute_uri(url.short_code) # Build the short URL using absolute URI
return render(request, 'index.html', {'short_url': short_url}) # Render template with short URL
return render(request, 'index.html') # Render default template for GET requests
# View function to redirect to original URL
def redirect_url(request, short_code):
url = get_object_or_404(URL, short_code=short_code) # Get the URL object by short code or return 404
return redirect(url.original_url) # Redirect to the original URL associated with the short code
Processing and forwarding requests

Step 4: Map URLs to views

  1. Define URL patterns: In the /usercode/urlshortener/shortener/urls.py file, map the views to URLs:

from django.urls import path
from . import views
urlpatterns = [
# URL pattern for the main page to shorten URLs
path('', views.shorten_url, name='shorten_url'),
# URL pattern to redirect based on the short code provided
path('<str:short_code>/', views.redirect_url, name='redirect_url'),
]
Defining views to URL mappings for the application
  1. Include the app URLs in the project: In the /usercode/urlshortener/urlshortener/urls.py file, include the shortener app URLs:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
# Admin site URL pattern
path('admin/', admin.site.urls),
# Include URLs from the 'shortener' app
path('', include('shortener.urls')),
]
Defining the URLs for the project

Step 5: Create a simple template

  1. Create a simple form template: In the /usercode/urlshortener/shortener/templates/index.html file, create a basic HTML form that takes the URL as input in a text box and displays the output right beneath it. Feel free to add any styling as per your preferences.

<!DOCTYPE html>
<html>
<body>
<div class="container">
<h1>Welcome to the URL Shortener</h1>
<!-- Form to submit the original URL -->
<form method="post">
<h2>Shorten Your URL</h2>
{% csrf_token %}
<input type="url" name="original_url" placeholder="Enter URL" required>
<button type="submit">Shorten</button>
</form>
{% if short_url %}
<!-- Display the short URL if available -->
<div class="short-url">
<p>Short URL: <a href="{{ short_url }}">{{ short_url }}</a></p>
</div>
{% endif %}
</div>
</body>
</html>
Designing the front end to input a URL and display its shortened version

Step 6: Run the server

  1. Start the Django development server: In the terminal, run the following command to start the Django development server and view your application in the browser:

python3 manage.py runserver
Command to run the Django application
  1. Test the URL shortener application: The complete application is created for you below. Run the application, enter a URL in the form, submit it, and you should get a shortened URL. You can then use this shortened URL in your browser to test the redirection.

The Django URL shortening application

Note: Once you get the shortened URL, paste that link in your own browser to view the webpage.

Conclusion

Setting up a scheduled job in Django lets developers optimize backend functionalities and saves a lot of time. By using this built-in tool, we can automate a recurring task, provide a unique user experience, and enhance application efficiency.

Copyright ©2024 Educative, Inc. All rights reserved