How to Create URL Shortener in Django?

Published On: 16/12/2022 | Category: Django

Hi Dev,

This example is focused on how to create url shortener in django. I would like to share with you url shortener in django. I explained simply step by step how to create a url shortener in python django. This article goes in detailed on how to make a url shortener in django.

One of the most popular applications of the Django Rest Framework is the display of API data in Django templates. You might need to use API data at some point in your projects. In this blog, we are going to learn How to display API response in HTML using Django Template.

Here i will give you we will help you to give example of django search autocomplete input field example. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
cd example
django-admin startapp core

Step 3: Update

Next, you need to add it in the file as follows:

Step 4: Create a Model

Now go for the models we will We'll call our single model Post and it will have just two fields: url and slug. And finally set __str__ to display the name of the post in admin interface.

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)

    def __str__(self):
        return f"Short Url for: {self.url} is {self.slug}"

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python makemigrations
python migrate
Step 5: Create a Form

In this step We need to create a form that will be used.

from django import forms

class UrlForm(forms.Form):
    url = forms.CharField(label="URL")

Step 6: Creating the Views

In this step, we need to create the views for performing fetch data from jsonplaceholder post api record.Open the core/ file and add:

from django.shortcuts import render, redirect
from .models import Url
from .forms import UrlForm
from django.contrib import messages
import random
import string

# Create your views here.
def urlShort(request):
    if request.method == 'POST':
        form = UrlForm(request.POST)
        if form.is_valid():
            slug = ''.join(random.choice(string.ascii_letters)
                           for x in range(10))
            url = form.cleaned_data["url"]
            new_url = Url(url=url, slug=slug)
            # request.user.urlshort.add(new_url)
            return redirect('/')
        form = Url()
    data = Url.objects.all()
    context = {
        'form': form,
        'data': data
    return render(request, 'url.html', context)

def urlRedirect(request, slugs):
    data = Url.objects.get(slug=slugs)
    return redirect(data.url)

Step 7: Creating Templates

Next, open the core/templates/url.html file and the add:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <style type="text/css">
            background-color: #f7fcff;
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header">
                        <h3>How to Create URL Shortener in Django? - <span class="text-primary"></span></h3>
                    <div class="card-body">
                        <form action="{% url 'urlShort' %}" method="POST">
                            {% csrf_token %}
                            <div class="row">
                                <div class="col-md-12">
                                    <input type="text" class="form-control" name="url">
                            <div class="row mt-2">
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-success">Submit</button>

                        <table class="table mt-4">
                                    <th>Old url</th>
                                    <th>New url</th>
                            {% for i in data %}
                            {% endfor %}

Step 8: Creating Urls

In this section, we’ll create the urls to access our views.Go to the core/ file and update it as follows:

from django.urls import path
from core import views

urlpatterns = [
    path("", views.urlShort, name="urlShort"),
    path("<str:slugs>", views.urlRedirect, name="redirect")

Next, we will require the modify the your root preoject folder lets update the file.

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

urlpatterns = [
    path('', include('core.urls')),

Step 8: Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000 address with a web browser.

I Hope It will help you....