Django URL Dispatcher Tutorial
Last Updated :
24 Sep, 2024
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
- open the urls.py file in our Django app
- Import the path() function from django.urls.
- 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.
Python
from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home_view),
path('about/', views.about_view),
]
Understanding Django’s URL dispatcher is fundamental for routing in web applications. To explore this and other advanced Django topics, the Django Web Development Course will help you achieve mastery.
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:
- Define the regular expression in url pattern and add capturing groups by the help of ‘()’ to collect values from the pattern.
- In the view function, include for each capturing group.
- 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’.
Python
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.
Python
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:
- In the path function specify the name ,with a string value.
- 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.
Python
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
Python
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.
Python
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.
Python
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’.
Python
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
Similar Reads
url - Django Template Tag
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
3 min read
Django Tutorial | Learn Django Framework
Django, built with Python, is designed to help developers build secure, scalable, and feature-rich web applications quickly and efficiently. Whether you're a beginner looking to create your first dynamic website or an experienced developer aiming to enhance your skills, this tutorial will guide you
11 min read
Comparing path() and url() (Deprecated) in Django for URL Routing
When building web applications with Django, URL routing is a fundamental concept that allows us to direct incoming HTTP requests to the appropriate view function or class. Django provides two primary functions for defining URL patterns: path() and re_path() (formerly url()). Although both are used f
8 min read
How to Create and Use Signals in Django ?
In this article, we'll dive into the powerful world of Django signals, exploring how to create and use them effectively to streamline communication and event handling in your web applications. Signals in DjangoSignals are used to perform any action on modification of a model instance. The signals ar
5 min read
URLField - Django Forms
URLField in Django Forms is a URL field, for input of URLs from an user. This field is intended for use in representing a model URLField in forms. The default widget for this input is URLInput. It uses URLValidator to validate that the given value is a valid URL. Syntax field_name = forms.URLField(*
5 min read
Django URL patterns | Python
Prerequisites: Views in Django In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration) Let t
2 min read
Browsable API in Django REST Framework
The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header. It helps us to use we
8 min read
Get the Current URL within a Django Template
Django, a high-level Python web framework, encourages rapid development and clean, pragmatic design. One common requirement when developing web applications is to access the current URL within a template. This can be useful for various purposes such as highlighting the active link in a navigation me
3 min read
Django URLResolver error
There are many errors that come when we create a project in Django. In this article, we will learn how to resolve such error "URLResolver error". What is URLResolver Error in Django? Url Resolver error in Django pops out when there is a mistake in your URL patterns configurations. This can be caused
4 min read
Custom Template Filters in Django
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database â SQLlite3, etc. What is filters in Django t
2 min read