In Django, you can use query parameters in URLs to pass additional information to your views. Query parameters are key-value pairs added to the end of a URL after a question mark (?
). Here's a step-by-step guide on how to use query parameters in Django URLs:
Define the URL pattern in urls.py
:
Open your urls.py
file and define the URL pattern. You can include the parameter names in angle brackets (< >
). These parameter names will be captured from the URL and passed to your view.
python# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('example/', views.example_view, name='example'),
]
Update your view to handle query parameters:
In your views.py
file, update the view function to handle the query parameters. You can use the request.GET
dictionary to access the parameters.
python# views.py
from django.shortcuts import render
def example_view(request):
# Access query parameters using request.GET.get('parameter_name', default_value)
parameter_value = request.GET.get('parameter_name', 'default_value')
# Your view logic here
return render(request, 'example_template.html', {'parameter_value': parameter_value})
Update the template to display the parameter value:
In your template file (example_template.html
), you can display the value of the query parameter.
html<!-- example_template.html -->
<h1>Example View</h1>
<p>Parameter Value: {{ parameter_value }}</p>
Include the query parameters in the URL:
When navigating to the URL, you can include query parameters by appending them to the URL after a question mark (?
). For example:
bashhttp://localhost:8000/example/?parameter_name=value
Replace http://localhost:8000
with your domain and port.
Now, when you access the /example/
URL with the specified query parameter, the value will be passed to the example_view
function, and you can use it in your view logic.