Create a URL Shortener app with Python and Django. Part-2
Photo by LinkedIn Sales Solutions on Unsplash |
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,
- URL: The Full URL that is provided by the user
- 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.
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.
READ: How 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.
Comments
Post a Comment