Skip to main content

Create a URL Shortener app with Python and Django. Part-2

Create a URL Shortener app with Python and Django. Part-2



Photo by LinkedIn Sales Solutions on Unsplash


To start the project you have to use the Django-admin command. This tutorial series is to teach how to create a URL Shortener app and I don't explain the very basics. Please let me know if you want a primary tutorial series in the comment section below.


1. Starting the project.



















2. Starting the app















To start a Django app we run the python manage.py [APP_NAME]  command.

2. Register the app

To tell Django to consider url_shortener as an app for our project we have to edit the settings.py file inside the Shortener Folder.









Add a line in the following format to the INSTALLED_APPS list.

 

[APP_NAME].apps.[APP_CONFIG_NAME]

 

To find the [APP_CONFIG_NAME], open the apps.py file in the app directory and you will see a class that inherits the AppConfig class. The name of that class is the name you want.

 

In my case it is UrlShortenerConfig.












3. Creating Models.


To Store the random slugs, we created with the corresponding full links, we have to use a database. Django models help us create these databases with just Python.

 

Here is the code.


 












Here I call my model Link and you can call it whatever you want. Our Link class has two properties,

  1.      URL: The Full URL that is provided by the user
  2.      Slug: The random, unique string we create for each URL. 



4. Writing the logic.


Our Logic is as described below






Now, let's write some codes to implement our logic. As you may already know, we always write the logic for our Django app in its views.py file.


For now, I am not going to use ajax for sending and receiving data but I promise to teach you how to implement ajax in our project later.


Here is our views.py file for the url_shortener  app.



from django.http import HttpResponse
from django.shortcuts import render
from . models import Link
import random
import string
# Create your views here.

def create_slug(size = 6, chars = string.ascii_lowercase+string.digits):
    return "".join(random.choice(chars) for _ in range(size))





def create(request):

    if request.method == 'GET':
        pass
    else:
        url = request.POST['url']
        slug = create_slug()

        while Link.objects.filter(slug=slug).exists():
            slug = create_slug()
       
        url = Link(
            URL = url,
            slug = slug,
        )
       
        url.save()
        context['slug'] = slug

       
   
    return render(request, 'url_shortener/create.html',context)




The create_slug function generates a random string for us to use as the Link's slug and in the create function, Django checks whether there is another link that uses the same slug. If yes, it creates a new slug and repeats the test.


READHow to generate a random string with Python.

At last, the function chooses a unique and random slug for the link and creates an instance of the Link model, and saves it. Then it renders a template with a context.


5. Setting Up Templates.


Templates are the HTML files that are rendered by Django. Here we create an absolutely simple HTML file ( aka template) to display a form and the shortened URL.

Create a template folder as shown in this file tree.



and tell Django to look for the templates in the templates folder by adding this line to your settings.py file.


















Now we can place any HTML file in the templates directory and tell Django to display the template whenever the user requests it.

Let's find out how to code our URL patterns and the templates in the next and last episode.

Stay tuned!


Comments

Trending Now

Find the Resultant vector of two Vectors With PYTHON!!

NEW ARTICLE:  How to Find the resultant of multiple vectors with Python! Using Python We can do many complex calculations. I learned how to calculate Resultant Vector using a formula with its size and direction in my Physics class. Then, I simply developed a CLI software to calculate the resultant of given two vectors Hope you like it :>) Follow me... Step :1 You need to install python on your computer. No matter what the operating system is you can find the ideal version of python from the official website of Python org And you will need a code editor like VS code and can download it with a simple Google search. (Hope you hate the first step Haha ) Step 2: we use the math module to calculate our resultant vector. The method I used as follows math.radians() : converts degrees to radians math.degrees() : converts radians to degrees math.sqrt()  : find the square root of a number math.atan() :find the tan inverse Step 3: the formula I used to calculate the size of the resultant is as

How to send and receive discord messages with your bot in 2023.

Hello everyone. Welcome back to the Blog of Chamodh today I will show you how to send and receive discord messages with your bot. Before getting started, I remind you that this is the second episode of the series How to make Discord bot in 2023 and if you haven't read the previous one, please read that first as I explain how to create your bot application and add it to a server there. READ:  https://blogofchamodh.blogspot.com/2023/02/how-to-make-your-own-discord-bot-2023.html We don't gonna use virtual environments, IDEs, or any other utility because we can use Replit for our coding purposes.  Let's Get Started. STEP1: Set up Replit It is really simple. Just go to  https://replit.com/~ and sign up if you have never used its service before and create a new Repl. I don't hope to guide you in this as this is an intermediate tutorial. Make sure to select Python as you create the new Repl because we are going to use Python for our back end. STEP 2: Get your token. To run ou