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.

  1. Python file named urls.
  2. routes
from django.urls import path
from . import views
  1. 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.

  1. When the root path is accessed, the request will be handled by the views.index function.
  2. When the /about/ path is accessed, the views.about function will be called to handle the request.
  1. 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.

  1. configuration settings file
  2. file for handling URLs
  3. 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.

bannerAds