A high-level Python web framework called Django uses the model-view-controller design pattern to give developers a disciplined way to create scalable and enduring web applications. It has many tools and built-in capabilities that make routine web development jobs easier.
In Django, URLs (Uniform resource locators) specify how incoming requests are translated to view functions or classes for processing and producing responses.
These patterns are defined in the project's URL configuration file (urls.py). A Django web application relies heavily on URLs to route and handles several endpoints, enabling users to access different pages or resources depending on the requested URL.
Customizing URLs in Django involves modifying the URL patterns in the project's URL configuration file (urls.py
) to match specific requirements. This can include changing URL paths, adding named URL patterns, including URL parameters, and more. By customizing URLs, developers can create clean, meaningful, and user-friendly URLs that align with the application's functionality and enhance the overall user experience.
Set up a Django project. After creating the Django project named my_project
, create an app in Django named my_app
.
After creating the app, list that app in INSTALLED_APPS
in setting.py
file of the project.
# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','my_app']
In Django, URLs and views collaborate to process incoming requests and deliver useful results. Specific URLs are mapped to associated views in the urls.py
URL configuration file. Views commonly specified in views.py
include the logic for processing requests, taking relevant actions, and producing answers.
In my_app/views.py,
create views for the customized URLs.
from django.shortcuts import renderfrom django.shortcuts import renderfrom django.http import HttpResponsedef password_reset(request):# Code to handle password reset confirmationreturn HttpResponse("Password reset confirmation view")def activation_view(request):# Code to handle account activationreturn HttpResponse("Account activation view")def home_view(request):return HttpResponse("Welcome to the homepage!")
password_reset(request):
Password reset requests are handled by the view function password_reset(request). When a user verifies their password reset request, it is responsible for implementing the logic and providing the proper response. In this instance, a HttpResponse
with the text “Password reset confirmation view” returned.
activation_view(request):
This view function handles the account activation procedure. It is in charge of handling the request for activation and activating the user’s account. Similar to the last example, this one returns a HttpResponse
with the phrase “Account activation view.”
home_view(request):
The homepage is rendered using this view function. A simple HttpResponse with “Welcome to the homepage!” is returned.
These view methods are often linked to specific URLs in the URL setup of your Django project, making them accessible to users via matching URLs. The views handle the logic for processing requests and providing pertinent replies, such as displaying templates or sending data back to the user.
You would need to map these views to URLs in the urls.py file of your Django project to use them. This mapping enables Django to direct incoming requests to the correct view function by linking the URLs to the respective views.
In my_project/urls.py
, set up the URL for the view we've created for the customized URLs.
"""my_project URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/3.2/topics/http/urls/Examples:Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: path('', views.home, name='home')Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))"""from django.contrib import adminfrom django.urls import pathfrom django.urls import path, includefrom my_app import viewsfrom my_app.views import home_viewfrom my_app.views import password_reset, activation_viewfrom django.urls import path, includeurlpatterns = [# ... other URL patterns from the project ...#path('api/auth/', include('my_app.urls')),path('', home_view, name='home'),path('custom/password-reset/', password_reset, name='password_reset'),path('custom/activate/', activation_view, name='activate'),# ... other URL patterns from the project ...]
The directory structure will look like this.
project_name/├── manage.py├── my_project/│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ ├── asgi.py│ └── wsgi.py└── your_app/├── __init__.py├── views.py└──apps.py
Now that the files have been all setup and the customized URLs have been created, you are all set to go.
Run the following command to start the server
python manage.py runserver
When you run the server, the web browser will first display the home_view
that you created in my_app/views.py
by using render()
. Now, you can open any of the other views that have been created by using the customized URL attached to it.
Open a web browser and enter the URL based on your local development server's address. For example, if your server is running at http://localhost:8000/
, you would enter the following URL.
http://localhost:8000/custom/password-reset/
Pressing enter will send the request to the specified URL. Django will route the request to the associated view function, password_reset
in this case.
Depending on how you have implemented the logic, you can observe the response generated by the view function. In this case, it will display the phrase "password reset confirmation view."
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
Free Resources