How to Create URL Shortener in 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 exampleStep 2: Create a App
cd example django-admin startapp core
Step 3: Update settings.py
Next, you need to add it in the settings.py file as follows:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ]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.
core/models.pyfrom 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 manage.py makemigrations python manage.py migrateStep 5: Create a Form
In this step We need to create a form that will be used.
core/forms.pyfrom 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/views.py file and add:
core/views.pyfrom 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) new_url.save() # request.user.urlshort.add(new_url) return redirect('/') else: 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:
/core/templates/url.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tuts-Station.com</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <style type="text/css"> body{ background-color: #f7fcff; } </style> </head> <body> <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">Tuts-Station.com</span></h3> </div> <div class="card-body"> <form action="{% url 'urlShort' %}" method="POST"> {% csrf_token %} <div class="row"> <div class="col-md-12"> <label>URL</label> <input type="text" class="form-control" name="url"> </div> </div> <div class="row mt-2"> <div class="col-md-12"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> <table class="table mt-4"> <thead> <tr> <th>Old url</th> <th>New url</th> </tr> </thead> {% for i in data %} <tbody> <tr> <td>{{i.url}}</td> <td>{{i.slug}}</td> </tr> </tbody> {% endfor %} </table> </div> </div> </div> </div> </div> </body> </html>
Step 8: Creating Urls
In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:
core/urls.pyfrom 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 urls.py your root preoject folder lets update the file.
example/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), 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 manage.py runserver
Next, go to the http://localhost:8000 address with a web browser.
I Hope It will help you....