How to Add URL Parameters to Django Template URL Tag?
Last Updated :
02 Sep, 2024
When building a Django application, it's common to construct URLs dynamically, especially when dealing with views that require specific parameters. The Django template language provides the {% url %}
template tag to create URLs by reversing the URL patterns defined in the urls.py
file. This tag becomes especially useful when we need to pass additional data through URLs, such as query parameters, to be used within our views.
Query parameters are the part of a URL that comes after the '?' and are used to send data to the server. Understanding how to correctly add these parameters is crucial for building dynamic and responsive web applications in Django. In this article, we will walk through the process of adding URL parameters to the Django template URL tag.
URL Parameters in Django
In Django, there are two main types of parameters we can pass in URLs:
Path Parameters: These are part of the URL path itself, such as /details/1/, where 1 is a parameter passed to the view.
Query Parameters: These are additional data appended to the URL after a '?', such as /details/1/?date=2024-01-01, where date=2024-01-01 is a query parameter.
Django’s url template tag allows us to generate URLs dynamically by inserting path parameters directly. However, adding query parameters requires a slightly different approach, where we manually append the parameters after the URL.
Adding URL Parameters to Django Template URL Tag
To understand how can we add pass URL parameters in Django, here we create a simple project and set up the environment to work with the URL tag.
1. Create the Project and App:
python -m venv venv
venv/Script/activate
django-admin startproject url_params_example
cd url_params_example
python manage.py startapp myapp
Configure settings.py: Add 'myapp' to the INSTALLED_APPS list in the settings.py:
INSTALLED_APPS = [
...
'myapp',
]
2. Create Views
Now, let's create a few views in myapp/views.py that will handle the our logic.
Also, we will make sure that each view should access a query parameter (date, month, or year) from the URL and captures the id from the path.
myapp/views.py
Python
from django.shortcuts import render
def details_view(request, id):
date = request.GET.get('date', 'Not provided')
context = {'id': id, 'date': date, 'type': 'Details'}
return render(request, 'myapp/display.html', context)
def summary_view(request, id):
month = request.GET.get('month', 'Not provided')
context = {'id': id, 'date': month, 'type': 'Summary'}
return render(request, 'myapp/display.html', context)
def report_view(request, id):
year = request.GET.get('year', 'Not provided')
context = {'id': id, 'date': year, 'type': 'Report'}
return render(request, 'myapp/display.html', context)
def index_view(request):
return render(request, 'myapp/index.html')
3. Define the URL Patterns
It's the time to map these views to urls. In myapp/urls.py, define the URL patterns that will handle different pages. Each URL will capture a path parameter:
myapp/urls.py
Python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index_view, name='index'),
path('details/<int:id>/', views.details_view, name='details'),
path('summary/<int:id>/', views.summary_view, name='summary'),
path('report/<int:id>/', views.report_view, name='report'),
]
Also, let's include these urls to our project urls.
url_params_example/urls.py
Python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Create the Template
Create a 'templates' directory and 'myapp' directory in it. Add a single template display.html that will display the passed parameters. This template will be used by all three views. This template dynamically displays the type of view, the ID, and the date (or month/year) passed through the query parameters.
templates/myapp/display.html
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ type }} View</title>
</head>
<body>
<h1>{{ type }} for ID: {{ id }}</h1>
<p>Date/Month/Year: {{ date }}</p>
</body>
</html>
Add URL Parameters in Another Template
To link to these views with query parameters, create another template (index.html) with links: This template demonstrates how to append query parameters to the URLs generated by the URL template tag.
templates/myapp/index.html
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>Links with URL Parameters</h1>
<ul>
<li><a href="{% url 'details' id=1 %}?date=2024-01-01">View Details for ID 1</a></li>
<li><a href="{% url 'summary' id=2 %}?month=August">View Summary for ID 2</a></li>
<li><a href="{% url 'report' id=3 %}?year=2023">View Report for ID 3</a></li>
</ul>
</body>
</html>
Run the Server
python manage.py runserver
These links will generate URLs that look like:
- /details/1/?date=2024-01-01
- /summary/2/?month=August
- /report/3/?year=2023
These URLs are designed to pass both path parameters and query parameters to the respective Django views.
Conclusion
Adding URL parameters to Django template URL tags is a powerful technique for passing dynamic data between views. By appending query parameters to the URLs generated in our templates, we can easily pass and retrieve additional data, making our web application more interactive and responsive to user input. This method is essential for features like filtering results, handling form submissions, and navigating between detailed views of different records.
Similar Reads
Boolean Operators - Django Template Tags
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
5 min read
How to add RSS Feed and Sitemap to Django project?
This article is in continuation of Blog CMS Project in Django. Check this out here - Building Blog CMS (Content Management System) with Django RSS (Really Simple Syndication) Feed RSS (Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a stan
3 min read
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
extends - Django Template Tags
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
2 min read
How to Add Data from Queryset into Templates in Django
In this article, we will read about how to add data from Queryset into Templates in Django Python. Data presentation logic is separated in Django MVT(Model View Templates) architecture. Django makes it easy to build web applications with dynamic content. One of the powerful features of Django is fet
3 min read
How to add AMP to Django Project?
A blog mostly needs content but that doesn't mean, your blog will be on top of Google search. For this you will need Speed, Security, user base and first of all search engines need to know that your blog exists. We will add AMP for speed. Â This article is in continuation of Blog CMS Project in Djang
4 min read
How to create Custom Template Tags in Django ?
Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed
4 min read
How Do You Pass Parameters to a Shiny App via URL in R
Shiny is an R package that makes it easy to build interactive web applications. Sometimes, you might want to pass information to your Shiny app through the URL so that the app can react to or use this information. This can be useful if you want to customize the app based on the URL or share specific
2 min read
How To Get URL And URL Parts In JavaScript?
In web development, working with URLs is a common task. Whether we need to extract parts of a URL or manipulate the URL for navigation, JavaScript provides multiple approaches to access and modify URL parts. we will explore different approaches to retrieve the full URL and its various components. Th
3 min read
lorem - Django Template Tags
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
2 min read