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.
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
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:
Step 1: Set up the Django project
Create a new Django project and application: Use the following terminal commands to create a Django project
urlshortenerand an applicationshortenerwithin the project:
django-admin startproject urlshortenercd urlshortenerpython3 manage.py startapp shortener
Add the application to the project's settings: Since the name of our application is
shortener, go to the/usercode/urlshortener/urlshortener/settings.pyfile and add'shortener'to the list ofINSTALLED_APPSas follows:
INSTALLED_APPS = [...'shortener',]
Note: The
/usercodedirectory is the default workspace directory on the Educative platform to build your application.
Define host names that your application is allowed to serve: Set
ALLOWED_HOSTS = ['*']in the/usercode/urlshortener/urlshortener/settings.pyfile to allow accepting requests from any domain or setALLOWED_HOSTS = ['<specific_url>']to restrict requests to a certain domain only.
Step 2: Define the URL model
Create the URL model: In the
/usercode/urlshortener/shortener/models.pyfile, define a simple model to store the input and respective shortened URLs in the database:
from django.db import modelsimport stringimport randomclass URL(models.Model):# Fields for the original URL and the shortened codeoriginal_url = models.URLField()short_code = models.CharField(max_length=6, unique=True)# Custom save method to ensure a short code is generated if not provideddef save(self, *args, **kwargs):if not self.short_code:self.short_code = self._create_unique_short_code() # Generate short code if not already setsuper(URL, self).save(*args, **kwargs)# Method to create a unique 6-character short codedef _create_unique_short_code(self):characters = string.ascii_letters + string.digitswhile True:short_code = ''.join(random.choices(characters, k=6))if not URL.objects.filter(short_code=short_code).exists():breakreturn short_codedef __str__(self):# Return the original URL when the instance is represented as a stringreturn self.original_url
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
charactersas a combination of both letters and digits.Line 20-21: This generates
short_codeusing therandom.choices()function from our defined set ofcharactersfor6characters. If the generatedshort_codealready exists in the database, it outputs it; otherwise, it regenerates it to ensure uniqueness.Line 22: This returns the unique
short_code.
Run migrations to create the database table: Run the following commands in the terminal to create the tables:
python3 manage.py makemigrationspython3 manage.py migrate
Step 3: Create views
Create views for URL shortening and redirection: In the
/usercode/urlshortener/shortener/views.pyfile, define the views as follows:
from django.shortcuts import render, get_object_or_404, redirectfrom django.http import HttpResponsefrom .models import URL# View function to handle URL shorteningdef shorten_url(request):if request.method == 'POST':original_url = request.POST['original_url'] # Get the original URL from POST dataurl, created = URL.objects.get_or_create(original_url=original_url) # Get or create URL the objectshort_url = request.build_absolute_uri(url.short_code) # Build the short URL using absolute URIreturn render(request, 'index.html', {'short_url': short_url}) # Render template with short URLreturn render(request, 'index.html') # Render default template for GET requests# View function to redirect to original URLdef redirect_url(request, short_code):url = get_object_or_404(URL, short_code=short_code) # Get the URL object by short code or return 404return redirect(url.original_url) # Redirect to the original URL associated with the short code
Step 4: Map URLs to views
Define URL patterns: In the
/usercode/urlshortener/shortener/urls.pyfile, map the views to URLs:
from django.urls import pathfrom . import viewsurlpatterns = [# URL pattern for the main page to shorten URLspath('', views.shorten_url, name='shorten_url'),# URL pattern to redirect based on the short code providedpath('<str:short_code>/', views.redirect_url, name='redirect_url'),]
Include the app URLs in the project: In the
/usercode/urlshortener/urlshortener/urls.pyfile, include the shortener app URLs:
from django.contrib import adminfrom django.urls import path, includeurlpatterns = [# Admin site URL patternpath('admin/', admin.site.urls),# Include URLs from the 'shortener' apppath('', include('shortener.urls')),]
Step 5: Create a simple template
Create a simple form template: In the
/usercode/urlshortener/shortener/templates/index.htmlfile, 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>
Step 6: Run the server
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
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.
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.
Free Resources