Django REST Framework is a robust and flexible toolkit for building Web APIs. It is written in python and allows the user to create some cool and awesome web applications. In this blog we will learn how to create a url shortener in django from scratch. This will be another good project for you to show. Now coming back to our project we will be creating a url shortener, a url shortener as the name suggests it helps to reduce the size of long urls’. We will be using python modules to generate short urls.

Create URL Shortener in Django from Scratch

Implementations

Step 1. Create Django Project

We are first going to create a django project and an app inside that project .

  1. Create a Django project.
django-admin startproject blog20

2. Create an app in that django-project.

python manage.py startapp urlshortner

3. Add your app name in installed apps.

Settings.py

INSTALLED_APPS = [
    'urlshortner',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Step 2. Add files and Folder to the Django Project

We need to create a template folder in the django folder and a urls.py file in the app folder.

  1. Create a new folder in the django folder(here,blog20) save it with the name template.
  2. Add the path for this template folder in blog20 > settings.py .

Settings.py

import os
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'template')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

3. Create a new file in the app folder(here, urlshortner) save it with the name urls.py .

4. Add path for this url.py file in blog20 > urls.py .

Urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('urlshortner.urls'))
]

Step3. Create URLshortener

For creating url shorteners we need a model that can store old and new urls. Then  we will implement everything normally our html files, urls.py and views.py. Here in views.py we will create a logic for generating short urls.

  1. Create a model in app_name (here, urlshortner ) > models.py and run the migrations.

Models.py

from django.db import models
# Create your models here.
class Url(models.Model):
    url = models.CharField(max_length=200)
    slug = models.CharField(max_length=15)

2. Create two html files one for taking input, here input is url that we want to shorten and second for showing converted urls.

Index.html

<html>
<head>
    <title>
        URL Shortner
    </title>
    <style>
        table {
            margin-left: 650px;
        }
    </style>
</head>
<body>
    {% if messages %}
    {% for message in messages %}
    {% if message.tags %}
    <script>alert("{{ message }}")</script> {% endif %}
    {% endfor %}
    {% endif %}
    <a href="urlcreated" style="font-size: 25px; ">View Url</a>
    <h1 align="center">URL Shortner</h1>
    <form action="createshorturl" method="POST">
        {% csrf_token %}
        <table>
            <tbody>
                <tr>
                    <td><label>URL</label></td>
                    <td><input type="text" name="url"></td>
                </tr>
                <tr>
                    <td><button>Submit</button></td>
                </tr>
            </tbody>
        </table>
    </form>
</body>
 
</html>

Urls.html

<html>
<head>
    <title>
        URL Shortner
    </title>
    <style>
        table {
            margin-left: 650px;
        }
    </style>
</head>
<body>
    <a href="/" style="font-size: 25px; ">Home</a>
    <table border="5px solid #000">
        <thead>
            <tr>
                <th>Old url</th>
                <th>New url</th>
            </tr>
        </thead>
        {% for i in url %}
        <tbody>
            <tr>
                <td>{{i.url}}</td>
                <td>{{i.slug}}</td>
            </tr>
        </tbody>
        {% endfor %}
    </table>
</body>
</html>

3. Provide path for the above html files and actions in app_name ( here, urlshortner ) > urls.py.

Urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('',views.index,name="index"),
    path('createshorturl',views.createshorturl,name="createshorturl"),
    path("urlcreated",views.urlcreated,name="urlcreated"),  
]

4. Create function for the path provided in urls file in app_name ( here, urlshortner ) > views.py.

The function createshorturl create slug based on taking 10 random ascii characters and making them a single string.

Views.py

from django.shortcuts import render,redirect
import random
from .models import Url
import string
from django.contrib import messages
# Create your views here.
def index(request):
    return render(request,'index.html')
 
def createshorturl(request):
    if request.method == 'POST':
        
            slug = ''.join(random.choice(string.ascii_letters)
                           for x in range(10))
            url = request.POST["url"]
            new_url = Url(url=url, slug=slug)
            new_url.save()
         
            messages.info(request,'New URL is created you can check it on view urls')
            return redirect('/')
  
def urlcreated(request):
    url=Url.objects.all()
    return render(request,'urls.html',{'url':url})

Output :-

Create URL Shortener in Django from Scratch
Index.html
Create URL Shortener in Django from Scratch
After creating new url
Create URL Shortener in Django from Scratch
Urls.html

Quick Revision

  1. Create your django project folder.
  2. Create an app folder in the django project folder.
  3. Add template folder in the django folder and provide its path in django_folder > settings.py .
  4. Create file named as urls.py in the app folder and provide its path in django_project > urls.py.
  5. Add path of index html page in app_folder > urls.py.
  6. Create function for the index html page in app_folder > views.py.
  7. Add html code for the  in django_project > template.

GitHub Link :-

https://github.com/jaya2320/blog_url_shortener

Conclusion

So, we learned how to create url shortener from scratch in  Django. I hope this blog will be useful for you and helps you to understand each and every step. Hope all your doubts get cleared. Thank you.