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...

Generate all possible phone numbers with Python | Generates Crores of Phone Numbers within minutes.

Recently,  I learned about itertools in python. Especially, about the functions permutations, combinations, and products and I tried to make a script that generates all phone numbers in our country. I bet your phone number is too on the list. let the hack begin!!! First, you need to install itertools in your computer  Simply open your terminal and type                sudo apt-get  install  -y python-more- itertools Then Write the code below from itertools import product file_name = "phonebook.txt" phonebook = open (file_name, 'a' ) prefixes = [ '+9471' ] product_a = product([ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' ], [ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' ], [ '1' , '2' , '3' , '4' , '5...