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 −

<!DOCTYPE html>
<html>
   <head>
      <title>Url Shortner</title>
   </head>
   <body>
      <div >
         <h1 >URL Shortner Application</h1>
         <form method="POST">{% csrf_token %}
            <input type="url" name="url" placeholder="Enter the link here" required>
            <button >Shorten URL</button>
         </form>
      </div>
      </div>
      {% if short_url %}
      <div>
         <h3>Your shortened URL /h3>
         <div>
            <input type="url" id="short_url" value={{short_url}}> <button name="short-url">Copy URL</button> <small id="copied" class="px-5"></small>
         </div>
         <br>
         <span><b>Long URL: </b></span> <a href="{{long_url}}">{{long_url}}</a>
      </div>
      {%endif%}
   </body>
</html>

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

Output

Updated on: 26-Aug-2021

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements