![]() |
VOOZH | about |
Django URL Shortener refers to a web application or reusable component built using Django that shortens long URLs into concise, shareable aliases making links easier to distribute on social media, emails, or documents while often tracking clicks for analytics.
Consider a project named 'urlShort' having an app named 'url'. Create a model which will store original URLs and their shortened slugs.
A model is required to store both the original URL and its shortened version (slug).
In models.py:
In the above model:
A form is required to allow users to enter the URL they want to shorten.
Create a forms.py:
This form will be used in views to get the user’s original URL and process it.
Views handle the core logic of the URL shortener. In url/views.py:
1. urlShort(): Handle URL Shortening
This function takes the original URL from the form, generates a random 10-character slug, saves it in the database, and displays all shortened URLs.
2. urlRedirect(): Redirect to the Original URL
This function retrieves the original URL based on the slug and redirects the user to it. In url/views.py:
The template displays the URL submission form and the list of shortened URLs.
Create a new file url/templates/index.html:
This template contains:
Connect the views to specific URLs by defining routes inside the urls.py file of the url app.
In url/urls.py:
In the above urls.py:
Before migrations can run, ensure your url app is listed in the project's settings file. Find the INSTALLED_APPS list and add your app:
INSTALLED_APPS = [
...
'url',
]
Run the following commands in your terminal to package your model changes and apply them to the database:
python manage.py makemigrations
python manage.py migrate
Start the Django development server to test the URL shortener. In the project’s root directory, run:
python manage.py runserver
Open a web browser and visit:
http://localhost:8000/
Output