Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Routing System

In this tutorial, we'll provide an overview of the Django routing system, which allows you to map URLs to specific views in your web application. We'll go through creating a Django project, setting up routing using the path and re_path methods, and using URL parameters.

  • Install Django (if you haven't already):
pip install django
  • Create a new Django project:
django-admin startproject routing_tutorial
cd routing_tutorial
  • Create a new Django app:
python manage.py startapp myapp
  • Register your app in routing_tutorial/settings.py. Add 'myapp' to the INSTALLED_APPS list:
INSTALLED_APPS = [
    # ...
    'myapp',
]
  • Create a view function in myapp/views.py:
from django.http import HttpResponse

def index(request):
    return HttpResponse("Welcome to the index page!")
  • Define URL patterns in myapp/urls.py. If this file doesn't exist, create it:
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
  • Include the app's URL patterns in the project's routing_tutorial/urls.py:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),
]
  • Create another view function in myapp/views.py:
def greet(request, name):
    return HttpResponse(f"Hello, {name}!")
  • Add a URL pattern with a URL parameter in myapp/urls.py:
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('greet/<str:name>/', views.greet, name='greet'),
]

In this example, <str:name> is a URL parameter that will be passed to the greet view function. The str part is a type converter that tells Django to expect a string, and name is the variable name that will be passed to the view function.

  • Optionally, if you want to use regular expressions in your URL patterns, you can use the re_path method. First, import it in myapp/urls.py:
from django.urls import path, re_path

Then, you can create a URL pattern using re_path:

re_path(r'^say_hello/(?P<name>\w+)/$', views.say_hello, name='say_hello'),

In this example, ^say_hello/ means the URL should start with "say_hello/". (?P<name>\w+) is a named capturing group that captures one or more word characters and passes them to the view function as the name variable. The $ symbol means the end of the URL string.

  • Start the development server:
python manage.py runserver
  • Visit the following URLs in your web browser to see the views in action:
  • http://127.0.0.1:8000/myapp/ - index page
  • http://127.0.0.1:8000/myapp/greet/John/ - greeting with name

This tutorial has shown you the basics of Django's routing system, including how to use the path and re_path methods and URL parameters.

  1. Django urlpatterns and Routing:

    • Description: In Django, urlpatterns define the routing configuration, mapping URLs to views or other urlpatterns.
    • Code:
      # urls.py
      from django.urls import path
      from . import views
      
      urlpatterns = [
          path('home/', views.home, name='home'),
          path('about/', views.about, name='about'),
      ]
      
  2. Django Routing vs. Dispatching:

    • Description: Routing involves mapping URLs to views, while dispatching is the process of determining which view should handle a specific URL.
    • Code:
      # urls.py
      from django.urls import path
      from . import views
      
      urlpatterns = [
          path('articles/', views.article_list, name='article-list'),
          path('articles/<int:article_id>/', views.article_detail, name='article-detail'),
      ]
      
  3. Django Views and URL Patterns:

    • Description: Views in Django handle the logic for processing requests and generating responses. URL patterns direct requests to these views.
    • Code:
      # views.py
      from django.shortcuts import render
      
      def article_list(request):
          # Logic to retrieve and render a list of articles
          return render(request, 'articles/list.html')
      
      def article_detail(request, article_id):
          # Logic to retrieve and render details of a specific article
          return render(request, 'articles/detail.html', {'article_id': article_id})
      
  4. Django URL Dispatching Mechanism:

    • Description: Django's URL dispatching mechanism determines which view should handle a specific URL based on urlpatterns.
    • Code:
      # urls.py
      from django.urls import path, include
      
      urlpatterns = [
          path('articles/', include('articles.urls')),
      ]
      
  5. Django path() vs re_path() in urlpatterns:

    • Description: Use path() for simple string-based URL patterns and re_path() for more complex patterns with regular expressions.
    • Code:
      # Using path()
      path('articles/<int:article_id>/', views.article_detail, name='article-detail')
      
      # Using re_path()
      re_path(r'^articles/(?P<article_id>\d+)/$', views.article_detail, name='article-detail')
      
  6. Django Routing Configuration:

    • Description: Routing configuration in Django involves defining urlpatterns to map URLs to views or other urlpatterns.
    • Code:
      # urls.py
      from django.urls import path, include
      
      urlpatterns = [
          path('articles/', include('articles.urls')),
      ]
      
  7. Django Route Patterns and Parameters:

    • Description: Use route patterns and parameters in urlpatterns to capture dynamic data from the URL.
    • Code:
      # urls.py
      path('articles/<int:year>/<int:month>/', views.article_archive, name='article-archive')
      
      # views.py
      def article_archive(request, year, month):
          # Use the captured year and month in the view logic
          return render(request, 'articles/archive.html', {'year': year, 'month': month})
      
  8. Django include() Function in urlpatterns:

    • Description: Use the include() function to include other urlpatterns from different files for modularity.
    • Code:
      # urls.py
      from django.urls import path, include
      
      urlpatterns = [
          path('articles/', include('articles.urls')),
      ]
      
  9. Django Reverse URL Routing:

    • Description: Reverse URL routing involves generating URLs based on view names and parameters using the reverse() function.
    • Code:
      # views.py
      from django.urls import reverse
      from django.shortcuts import redirect
      
      def redirect_to_home(request):
          # Redirect to the 'home' URL pattern dynamically
          home_url = reverse('home')
          return redirect(home_url)
      
  10. Django URL namespaces and Routing:

    • Description: Use URL namespaces to organize and group related URL patterns, preventing naming conflicts.
    • Code:
      # urls.py (project-level)
      from django.urls import path, include
      
      urlpatterns = [
          path('articles/', include('articles.urls', namespace='articles')),
      ]
      
      # urls.py (app-level - articles)
      from django.urls import path
      
      app_name = 'articles'
      urlpatterns = [
          path('list/', views.article_list, name='article-list'),
      ]
      
  11. Django Dynamic URL Routing:

    • Description: Dynamic URL routing involves capturing values from the URL and using them in the view.
    • Code:
      # urls.py
      path('articles/<int:article_id>/', views.article_detail, name='article-detail')
      
      # views.py
      def article_detail(request, article_id):
          # Use the captured article_id in the view logic
          return render(request, 'articles/detail.html', {'article_id': article_id})
      
  12. Django route() Method in urlpatterns:

    • Description: Use the route() method in views to generate URLs for dynamic routing within the app.
    • Code:
      # views.py
      from django.urls import reverse
      from django.shortcuts import redirect
      
      def redirect_to_category(request, category_id):
          # Redirect to the 'category-detail' URL pattern dynamically
          category_url = reverse('category-detail', args=[category_id])
          return redirect(category_url)
      
  13. Django App-Level URL Routing:

    • Description: Define URL patterns at the app level to organize and route requests for that specific app.
    • Code:
      # urls.py (app-level)
      from django.urls import path
      
      urlpatterns = [
          path('list/', views.item_list, name='item-list'),
      ]