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

Let's talk about cryptography.

Have you ever heard of cryptography?  People write their diaries every day. For many of them, their diary is one of their best friends to whom they tell their every secret. What happens when someone else finds such a diary? That would freak out the dairy's owner for sure. Also, it might put their lives in danger. Wise men always hide their diaries so no one else finds it.  But legends hide their message so that only they can read what they wrote. So even if the diary is found by someone else, they cannot know the secrets. for example, I wrote this in my diary today.   P dyval h isvn wvza hivba jyfwavnyhwof avkhf Can you understand it? This is just a very primitive level of cryptography yet powerful enough to hide what I wrote from 90% of people. I will discuss this type of cryptography in the next blog post. The human used cryptography from the very beginning to share their messages in secret and conceal their inventions. As you may know, many people tried to find a recip...

How to make a your own Discord bot with Python in 2023. #01

I'm sure that you have heard of discord bots way before reading this article. But have you ever tried to make your own bot with Python? If not, this is the time. Let's get started. Over time tons of discord bot tutorials have been published, but if you follow them they don't help you to build a functional bot because many of the packages used in them are updated and no longer support older syntaxes. Here is the full guide to creating your own Discord Bot in 2023 with Python. STEP 1: Create a Discord account First of all, we have to set up a developer account to create the bot. Actually, you can use your ordinary discord account to access the discord developer portal, but it is highly recommended to create a separate account for development purposes. You can create a new discord account with this link:  https://discord.com/register STEP 2: Create a new Application After creating the discord account, you have to go to the discord developer portal and sign in with your newly-c...