Open In App

Django URL Dispatcher Tutorial

Last Updated : 25 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the Django application URL Dispatcher is used to map the URL with view, which in turn helps to handle the request and produce a response. In this article, we will learn all the concepts related to the Django URL Dispatcher.

Methods of Using Django URL Dispatcher

  • Creating Url Patterns in Django
  • Using Regular Expression Captures in Django URL Patterns
  • Naming URL Patterns in Django
  • Inverting URL Patterns in Django
  • Using Namespaces in Django URL Patterns
  • Using Class-Based Views in Django URL Dispatcher

Creating Url Patterns in Django

In Django, URL patterns are the fundamental concept that is used to map URLs (Uniform Resource Locators) to views, by which we can specify how different URLs in your web application should be handled. URL patterns are defined in your Django project’s urls.py file. Let us understand with this example:

To create a URL Pattern we should

  1. open the urls.py file in our Django app
  2. Import the path() function from django.urls.
  3. Define a list of URL patterns

In this example, we’ve defined two URL patterns, ‘/home/’ and ‘/about/’, and specified which view functions should handle these URLs.

Python3




from django.urls import path
from . import views
 
urlpatterns = [
    path('home/', views.home_view),
    path('about/', views.about_view),
]


Using Regular Expression Captures in Django URL Patterns

If we want to extract the value from urls then pass it to views than we can do it with the help of regular expression captures .The extracted value then can be used as according to the need in the view function.

To use the Regular Expression capture follow the following steps:

  1. Define the regular expression in url pattern and add capturing groups by the help of ‘()’ to collect values from the pattern.
  2. In the view function, include for each capturing group.
  3. When the url pattern is matched ,the matched view function is called.

In below code the 3rd URL pattern is dynamic and captures an integer value called blog_id from the URL. For example, if you access http://yourdomain.com/blog/1/, it will display the detail page for the blog post with an ID of 1. The name of this URL pattern is ‘blog_detail’.

Python3




from django.urls import path
from . import views
 
urlpatterns = [
    path('', views.home, name='home'),
    path('blog/<int:blog_id>/', views.blog_detail, name='blog_detail'),
    
]


views.py: The view.py code for the above urls is shown below. In the below code ‘home’ is a basic view function. The ‘blog_detail’ is a view function in which the value captured value from url is passed as argument here. The argument here is ‘blog_id’ . This can be used inside our view function according to the need.

Python3




from django.shortcuts import render
from django.http import HttpResponse
 
 
def home(request):
    return HttpResponse("Welcome to our website!")
 
def blog_detail(request, blog_id):
    blog_post = {'id': blog_id, 'title': 'Sample Blog Post', 'content': 'This is the content of the blog post.'}
    context = {'blog_post': blog_post}
    return render(request, 'blog_detail.html', context)


Naming URL Patterns in Django

We can name our url pattern in Django so that it makes our work easy while refering to them in our code and html files.

To give a name to the url pattern we should follow the following steps:

  1. In the path function specify the name ,with a string value.
  2. In the templates, use the {% url %} and in the code use the reverse() function to refer to the named URL pattern.

Let us understand with this example:

In this Django URL configuration, we have assigned names to two URL patterns: ‘home’, ‘about’. These names help us refer to these URLs in our code, making it more readable and maintainable.

Python3




from django.urls import path
from . import views
 
urlpatterns = [
    path('home/', views.home, name='home'), 
    path('about/', views.about, name='about'),
]


Use in HTML template

We can use the name of the url pattern as :

{% url 'home' %}

For Example:

HTML




<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<a href="{% url 'home' %}">HOME</a>
</body>
</html>


Inverting URL Patterns in Django

In Django, inverting URL patterns refers to the process of reversing a URL to its corresponding view or URL pattern name. This is particularly useful when we want to generate URLs dynamically in our views or templates without hardcoding them.

We can invert URL patterns in Django using two primary methods:

  • Using the {% url %} template Tag

In Django templates, we can use the {% url ‘url_name’ %} template tag to reverse a URL based on its name. Here, ‘url_name’ should match the name assigned to the URL pattern in your urlpatterns.

<a href="{% url 'home' %}">Home</a>

  • Using the reverse() function in views

In your Python code (views, models, etc.), you can use the reverse() function to reverse a URL based on its name. Import it from django.urls and pass the URL pattern name as an argument. This will generate the URL for the ‘home’ URL pattern and perform a redirect.

Views.py

Python3




from django.urls import reverse
from django.shortcuts import redirect
 
def my_view(request):
    return redirect(reverse('home'))


Using Namespaces in Django URL Patterns

In Django, namespaces are used to organize URL patterns and prevent naming conflicts when multiple applications are integrated into a single project. Namespaces allow us to group URLs under a specific namespace or prefix, making it easier to manage and distinguish different parts of your application.

Example: Here is how we can use namespaces in Django URL patterns:

In the project’s main urls.py file, include your app’s URLs using the include() function with the namespace parameter.

Python3




from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp1/', include('myapp1.urls', namespace='myapp1')),
    path('myapp2/', include('myapp2.urls', namespace='myapp2')),
]


To reference URLs with namespaces in your templates or views, use the {% url %} template tag or the reverse() function with the format ‘namespace:url_name’. For example:

<a href="{% url 'namespace:url_name'' %}">Home</a>

Class-Based Views in Django URL Dispatcher

In Django, you can use class-based views (CBVs) to handle URL routing and view logic. Class-based views provide a more organized and reusable way to structure your views compared to function-based views .

Creating a Class-Based View:

To create a class-based view, define a Python class that inherits from one of Django’s provided generic view classes or create your own custom class. For example, let’s create a simple class-based view for displaying a list of items:

Example: In this example, we’ve created a class called ItemListView that inherits from View and defines a get method to handle GET requests.

Python3




from django.views import View
from django.http import HttpResponse
 
class ItemListView(View):
    def get(self, request):
        items = ["Item 1", "Item 2", "Item 3"]
        return HttpResponse("\n".join(items))


Mapping the Class-Based View to a URL

To map your class-based view to a URL, you can use the as_view() method of your view class when defining URL patterns in your app’s urls.py file:

Here, we’ve associated the ItemListView class-based view with the URL pattern ‘items/’ and given it the name ‘item-list’.

Python3




from django.urls import path
from .views import ItemListView
 
urlpatterns = [
    path('items/', ItemListView.as_view(), name='item-list'),
]


So, Now you have the knowledge about the URL dispacting in Django



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads