Open In App

How to Add URL Parameters to Django Template URL Tag?

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads