Django Framework : Build URL Shortener Application Using Django and Pyshorteners

Jan 22 2024 . 5 min read
unsplashimagePhoto by Bilal O. on Unsplash

In this article, we are going to build a simple URL Shortener application using django and pyshortener package, that will going to short the long urls, so let's dive into.


img

Install Dependencies

We need to install these two dependencies to start with this project :


Install django and pyshorteners by this command

pip install django pyshorteners

It will install both dependencies in a single hit. Let's dive next to setup our django project.

Setup the Django Project

First, let's create a setup a simple django project by following these instructions :


  1. Let's create a django project i am giving a project name `urlshortener`.
  2. django-admin startproject urlshortener

  3. Next move inside to `urlshortener` project.
  4. cd urlshortener

  5. Now Let's create a app i am giving a app name `main`.
  6. python3 manage.py startapp main

  7. Next, register our app under `INSTALLED_APPS`.
  8. settings.py
    1. INSTALLED_APPS = [
    2.    ...
    3.    'main.apps.MainConfig'
    4.    ...
    5. ]

  9. All set, our project is setup successfully. Cheers

Design the URL Shortener Application UI

Next we are going to build the UI for our URL Shortener application using `django templates`.


We will create a `templates/url-shortener.html` folder and file inside our `main` app.

Next, we are going to write the UI code for our url shortener application in `url-shortener.html` template file.

url-shortener.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <meta charset="utf-8" />
  5.     <meta name="viewport" content="width=device-width, initial-scale=1" />
  6.     <title> URL Shortener <title/>
  7.     <!-- Boostrap CDN -->
  8.     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" />
  9.     <!-- Google fonts CDN -->
  10.     <link rel="preconnect" href="https://fonts.googleapis.com">
  11.     <rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  12.     <href="https://fonts.googleapis.com/css2?family=Darker+Grotesque:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
  13.     <!-- CSS Code -->
  14.     <style>
  15.        body{
  16.          font-family: 'Darker Grotesque', sans-serif;
  17.        }
  18.     </style>
  19.   </head>
  20.   <body className="bg-light">
  21.     <div className="container" style="width: 40%;margin-top: 5rem;">
  22.       <!-- Flash Message -->
  23.       <div className="p-5 text-center shadow bg-white" style="border-radius: 15px;">
  24.         {% if messages %}
  25.           {% for message in messages %}
  26.             <div className="alert alert-success text-center fs-5">
  27.               {{message}}
  28.             </div>
  29.           {% endfor %}
  30.         {% endif %}
  31.       </div>
  32.       <!-- Url Shortener Form -->
  33.       <h1>URL Shorter Application</h1>
  34.       <div className="mt-5">
  35.         <form action="" method="post">
  36.           {% csrf_token %}
  37.           <input type="url" name="url" value="{{url}}" required className="form-control py-3" placeholder="Enter long link here">
  38.           <div className="mt-3 d-grid">
  39.             <button className="btn btn-primary p-3 fs-4 text-white">Shorten url<button/>
  40.           </div>
  41.         </form>
  42.       </div>
  43.       <!-- Result Container -->
  44.       {% if messages %}
  45.         <div className="mt-5 bg-white border p-3 shadow" style="border-radius: 15px;">
  46.           <div className="d-flex align-items-center justify-content-between">
  47.             <span id="short-url" className="fs-5">{{short_url}}</span>
  48.           </div>
  49.         </div>
  50.         <div className="mt-3">
  51.           <a href="" className="btn btn-success btn-sm fs-6">Shorten Another</a>
  52.         </div>
  53.       {% endif %}
  54.     </div>
  55.     <!-- Javascript Code -->
  56.     <script>
  57.       const copy_url = ()=>{
  58.         const short_url = document.getElementById("short-url").innerText
  59.         navigator.clipboard.writeText(short_url);
  60.       }
  61.     </script>
  62.   </body>
  63. </html>

Write the URL Shortener logic in view function

Next, we are going to create a view function, there we will implement the logic for url shortener

views.py
  1. from django.shortcuts import render
  2. import pyshorteners
  3. from django.contrib import messages
  4. def url_shortener(request):
  5.     try:
  6.         short_url = ""
  7.         url = ""
  8.         if request.method == "POST":
  9.              shortener = pyshorteners.Shortener()
  10.              url = request.POST.get("url")
  11.              short_url = shortener.tinyurl.short(url)
  12.              messages.success(request, "Generated")
  13.         return render(
  14.             request,"url-shortener.html", {"short_url": short_url, "url": url}
  15.         )
  16.     except:
  17.         returnrender(request, "url-shortener.html")

Next, just link the url to this view

urls.py
  1. from .views import url_shortener
  2. from django.urls import path
  3. urlpatterns = [
  4.     path("", url_shortener, name="url-shortener"),
  5. ]

Conclusion

This is the simple url shortener application we have build in the aricle. You can even add more features to this url shortener application like generate QRCode for this url etc.

You can find the complete code of this project on my github account. If you want add something you can feel free to reach out to me.