In this tutorial, I’ll demonstrate how to build a URL shortener with Django. The URL shortener gives a shortened link for any webpage and on visiting that link you will be redirected to the original webpage.

Set up your Django project:

Firstly to create a Django project, we need to have Django installed in our system. After installation, create a Django project named ‘urlshorten’, and then create an app called ‘main’ inside our project. Open the command-line terminal and run the following commands for the same.

 pip install Django
 django-admin startproject urlshorten
 cd urlshorten
 python manage.py startapp main 

Now open the project in any code editors, I personally prefer VsCode, you can also use Sublime Text, Atom etc.

Open settings.py and add the newly created app ‘main’ in the INSTALLED_APPS section.

#in settings.py 
INSTALLED_APPS = [ 
 'django.contrib.admin', 
 'django.contrib.auth', 
 'django.contrib.contenttypes', 
 'django.contrib.sessions', 
 'django.contrib.messages', 
 'django.contrib.staticfiles', 
 'main', 
 ] 

Now create a new file shorten.py to issue a token i.e. a string of some characters which will be used as our shortened link later.

So, the shorten.py file will look like this:

import random 
import string 
class short: 
  token_size = 5;

  def __init__(self, token_size=None):
    self.token_size = token_size if token_size is not None else 5
 
  def issue_token(self): 
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(self.token_size)) 

Here I have declared the token size to be 5, you can vary it depending on the number of characters you wish to have in your shortened link.

Here two functions are used, the first function sets the token size to 5 if the token size is not set. The second function is used to generate a random set of characters of the specified token size which serves as the shortened link.

Now we have to create the models, for that go to models.py file in-app ‘main’. Modify models.py as shown below

 
 from django.db import models 

 class short_url(models.Model):
   short_url = models.CharField(max_length = 20) 
   long_url = models.URLField("URL", unique=True)  

Here short_url and long_url fields store the token corresponding to a webpage and its original webpage link respectively.

Now as we have created tables, we need to perform migrations. Type in the following commands in the command line

 python manage.py makemigrations
 python manage.py migrate 

Now let’s create the forms.py file for registering new entries to our database. Modify forms.py file as shown below:

 
 from django import forms
 from .models import short_url 

 class UrlForm(forms.ModelForm): 
   class Meta: 

      model = short_url 
      fields = ['long_url'] 

After that, open views.py file and add the following code there:

 
from django.shortcuts import render, redirect 
from .models import short_url
from .forms import UrlForm
from .shorten import short 

def realurl(request, token):
  long_url = short_url.objects.filter(short_url=token)[0] 
  return  redirect(long_url.long_url) 

def shortfn(request):
  form = UrlForm(request.POST) 
  token = " "
  if request.method == 'POST': 
    if form.is_valid():
      NewUrl = form.save(commit=False) 
      token = short().issue_token() 
      NewUrl.short_url = token 
      NewUrl.save() 
  else:
      form = UrlForm() 
      token = " Invalid Url" 
      return render(request, 'home.html', {'form': form, 'token': token}) 

Use of shortfn():

The function shortfn() sends form to the user on receiving a POST request. The variable ‘token’ will store the token generated and both the token and the link will be stored in the database using the .save() method. If the form is valid, we will generate the token and save both the token and original URL in the database.

Use of realurl() :

The function realurl() is used for redirecting to the original webpage on visiting the shortened link.

Now let’s create a urls.py file inside the app ‘main’. Modify it as follows:

 
from django.urls import path 
from . import views 
 
urlpatterns = [ 
   path('', views.shortfn , name="shortfunction"), 
   path('<str:token>', views.realurl, name="realurl") 
 ] 

After that, modify the project level urls.py file as shown below:

 
from django.contrib import admin 
from django.urls import path, include 

 urlpatterns = [
   path('admin/', admin.site.urls), 
   path('', include('main.urls')), 
 ] 

After that, we will create a folder named templates inside our app ‘main’. Create a html page home.html inside templates and edit it as follows:

 
<!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> 

So, the script part in home.html will look as shown above. I’ve added some CSS to make the home page look better. We define a form here with POST method. Here forms.as_p is used to render Django forms as paragraph. Finally we display the shortened URL for a given large URL.

Now go to the command line and type in:

 
 python manage.py runserver

So this will display the home page:

build a URL Shortener with Django

As a result, we can see on giving the large URL in the field and pressing submit, a shortened link is returned.