Django URL Routes: Step-by-Step Tutorial
In Django, you can create routes by defining URL routes in the project’s urls.py file. Here is a simple example.
- Python file named urls.
- routes
from django.urls import path
from . import views
- Define URL routing, for example:
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
]
In the example above, we have defined two URL routes.
- When the root path is accessed, the request will be handled by the views.index function.
- When the /about/ path is accessed, the views.about function will be called to handle the request.
- views.py refers to the Python file that contains the views (or handlers) for different URL patterns in a Django web application.
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def about(request):
return render(request, 'about.html')
In the example above, the index and about functions handle requests for the root path and the /about/ path, respectively, and return the corresponding HTML pages.
- configuration settings file
- file for handling URLs
- List of applications that have been installed.
INSTALLED_APPS = [
...
'myapp',
...
]
By following the above steps, we can create and define URL routes in Django. When a user accesses the corresponding path, Django will use the route to find the appropriate view function to handle the request and return a response.