In this tutorial, we’ll dive into the fascinating world of web development with Django by creating a powerful URL shortener. A URL shortener is a handy tool that takes lengthy web addresses and converts them into compact, easy-to-share links. Users can then click on these shortened links to be redirected to the original webpage. Let’s embark on this journey of building a URL shortener with Django step by step.
Step 1: Setting Up Your Django Project
Before we start coding, ensure that you have Django installed on your system. If you haven’t already, you can quickly install it using pip:
pip install Django
Once Django is installed, create a new Django project called ‘myproject’ and then create an app within this project named ‘myapp’. Open your command-line terminal and execute the following commands:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
Now that we have our project structure in place, you can open it in your preferred code editor. I recommend using VSCode, but you can choose any code editor that suits your preferences.
In your project’s settings.py
file, include the ‘myapp’ app in the INSTALLED_APPS
section like this:
# in settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
Step 2: Creating the URL Shortener Logic
Our next step is to create a Python file named shorten.py
within the ‘myapp’ app to handle the URL shortening logic. This logic will generate unique tokens that we’ll use as shortened links.
import random
import string
class Shortener:
token_size = 5
def __init__(self, token_size=None):
self.token_size = token_size if token_size is not specified else 5
def generate_token(self):
letters = string.ascii_letters
return ''.join(random.choice(letters) for _ in range(self.token_size))
The Shortener
class defined above generates random tokens with the specified length, which will serve as our shortened URLs. You can easily adjust the token_size
variable to customize the length of your shortened links.
Step 3: Defining Database Models
In the ‘myapp’ app’s models.py
file, we need to define the database models for our URL shortener. These models will represent the shortened URL and its corresponding original URL.
from django.db import models
class ShortenedURL(models.Model):
short_url = models.CharField(max_length=20)
long_url = models.URLField("URL", unique=True)
Our ShortenedURL
model includes fields for the shortened URL (short_url
) and the original URL (long_url
).
Step 4: Performing Database Migrations
Now that we’ve defined our models, let’s create and apply database migrations using the following commands:
python manage.py makemigrations
python manage.py migrate
Step 5: Creating Forms
To allow users to submit URLs for shortening, create a forms.py
file in the ‘myapp’ app:
from django import forms
from .models import ShortenedURL
class UrlForm(forms.ModelForm):
class Meta:
model = ShortenedURL
fields = ['long_url']
This form, named UrlForm
, will handle user submissions for URL shortening.
Step 6: Implementing Views
In your ‘myapp’ app’s views.py
file, add the following code:
from django.shortcuts import render, redirect
from .models import ShortenedURL
from .forms import UrlForm
from .shorten import Shortener
def redirect_to_original_url(request, token):
long_url = ShortenedURL.objects.filter(short_url=token)[0]
return redirect(long_url.long_url)
def shorten_url(request):
form = UrlForm(request.POST)
token = ""
if request.method == 'POST':
if form.is_valid():
new_url = form.save(commit=False)
token = Shortener().generate_token()
new_url.short_url = token
new_url.save()
else:
form = UrlForm()
token = "Invalid URL"
return render(request, 'home.html', {'form': form, 'token': token})
The redirect_to_original_url
function handles the redireccstion to the original URL when users visit a shortened link. The shorten_url
function manages form submissions for URL shortening.
Step 7: Configuring URL Patterns
Create a urls.py
file within the ‘myapp’ app and configure your URL patterns as follows:
from django.urls import path
from . import views
urlpatterns = [
path('', views.shorten_url, name="shorten_url"),
path('<str:token>', views.redirect_to_original_url, name="redirect_to_original_url"),
]
Now, update the project-level urls.py
file as follows:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Step 8: Creating the HTML Template
Within the ‘myapp’ app, create a ‘templates’ folder if it doesn’t already exist. Inside this folder, create an HTML file named home.html
with the following content:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>URL Shortener</title>
</head>
<style>
body {
height: 100vh;
background-color: silver;
font-family: 'Times New Roman';
align-content: center;
display: flex;
justify-content: center;
align-items: center;
}
</style>
<body>
<div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" name="button">Submit</button>
</form>
<h4>Shortened URL is: {{ request.get_host }}/{{ token }}</h4>
</div>
</body>
</html>
This HTML template provides a user-friendly interface for submitting URLs and displaying shortened links.
Step 9: Running Your Django Application
Finally, launch the Django development server by running the following command:
python manage.py runserver
Visit the provided URL in your web browser to access your freshly created URL shortener. You can now submit long URLs and receive shortened links in return.
Congratulations! You’ve successfully built a URL shortener using Django. This project is an excellent starting point for further customization and enhancement according to your specific needs. Happy coding!
Find this tutorial on Github.