Making a URL shortner app in Django

In this article, we will see how to make a URL shortner app in Django. It is a simple app which will convert a long URL into a short one. We will achieve this using a Python library, not any Django-specific library, so you can use this code in any Python project.

First of all, create a Django project and an app. Do some basic settings like including urls of app and including app in INSTALLED_APPS in settings.py.

Example

Install the pyshorteners module −

pip install pyshorteners

In app's urls.py

from django.urls import path
from .views import url_shortner

urlpatterns = [
   path('', url_shortner.as_view(), name="url-shortner"),
]

Here we set the viewset as view on home url.

Now in views.py

from django.shortcuts import render
import pyshorteners
from django.views import View

class url_shortner(View):
   def post(self, request):
      long_url = 'url' in request.POST and request.POST['url']
      pys = pyshorteners.Shortener()
      short_url = pys.tinyurl.short(long_url)
      return render(request,'urlShortner.html', context={'short_url':short_url,'long_url':long_url})

   def get(self, request):
      return render(request,'urlShortner.html')

Here we created a view with two request handler functions, get handler will render the frontend html and post handler will get the long URL and re-render our frontend with the short URL.

Create a templates folder in app's directory and add urlShortner.html in it and write this −


   
      Url Shortner
   
   
      
         

URL Shortner Application

         
{% csrf_token %}                                  
     
            {% if short_url %}      
         

Your shortened URL /h3>          
                     
         
         Long URL: {{long_url}}      

      {%endif%}    

This is the frontend which will take the long URL and send the request, then it returns the short URL.

Output

Updated on: 2021-08-26T12:27:32+05:30

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements