How I Built a URL Shortener using Django (Part 2)

Devtekk
Satyam Kulkarni
Published in
3 min readOct 8, 2020

Building a URL Shortener, Is one of the Best Beginner Project to hone your Skills

Photo by Hitesh Choudhary on Unsplash

If you haven’t read First Part, I highly encourage you to read it first.

Let’s Start to Build our App

First of all, we need a Database to store our Shorten URL’s. For That, We need to create a Schema for our Database Table in models.py.

models.py

from django.db import modelsclass UrlData(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}"

Above Code Creates a Table UrlData in our Database with Columns url, slug. We will use url column to store Original URL and slug to store 10-character string which will be used for shortening the URL.

For Example,

Original URLhttps://medium.com/satyam-kulkarni/

Shorten Form https://localhost:8000/sEqlKdsIUL

URL’s maximum length is 200 Characters and Slug’s maximum length is 15 (Considering our Website’s Address)

After Creating Models for our Website, Let’s create some Forms for taking input from User.

Create a forms.py in our Django App Folder.

forms.py

from django import formsclass Url(forms.Form):
url = forms.CharField(label="URL")

We simply import forms from django and create a Class Url which we will use in views.py and render it in our html.

Url form has only a url field to take input of Original URL.

Now, We will create the Interface of our App using views.py.

Let’s divide this part in Functions.

urlShort()— This Function is where our Main Algorithm works. It takes a url from form after User sbmits it, then it generates a Random Slug which is then stored in Database with Original Url. It is also the function which render index.html (entrypoint of our app)

views.py urlShort()

def urlShort(request):
if request.method == 'POST':
form = Url(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 = UrlData(url=url, slug=slug)
new_url.save()
request.user.urlshort.add(new_url)
return redirect('/')
else:
form = Url()
data = UrlData.objects.all()
context = {
'form': form,
'data': data
}
return render(request, 'index.html', context)

urlRedirect() — This function tracks the slug to Original URL and redirects it to Original URL.

views.py urlRedirect()

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

Before Running This App, We need to specify URL paths in App’s urls.py

urls.py

from django.urls import path
from . import views
app_name = "url"
urlpatterns = [
path("", views.urlShort, name="home"),
path("u/<str:slugs>", views.urlRedirect, name="redirect")
]

So we are fine and Let’s Run this App

Open Console in Main Project Directory.

console

python manage.py runserver
Console

Let’s See What our Final Product look likes

FInal Website

Added a CSS little bit..

We will end Last Part of this Series.

For Video Series — https://youtu.be/xnw3l8cTNFI

Peace Out✌️

--

--

Devtekk
Satyam Kulkarni

I am Satyam Kulkarni, a Professional Web Developer and a content writer and also the Author of DevTekk. I will write about Programming and related Stuff