Reputation: 10143
I'd like to add request parameters to a {% url %}
tag, like ?office=foobar
.
Is this possible? I can't find anything on it.
Upvotes: 153
Views: 103265
Reputation: 1297
Starting from Django 5.1 there is a dedicated template tag querystring
Basic usage:
{% querystring size="M" %}
Upvotes: 0
Reputation: 4319
Tried all the above, nothing worked.
My system has:
Here's what worked for me:
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('single/', views.single, name='single'),
]
views.py
def single(request):
url = request.GET.get('url')
return HttpResponse(url)
Calling from .html file
<a href={% url 'single' %}?url={{url}} target="_self">
Broswer URL
http://127.0.0.1:8000/newsblog/single/?url=https://www.cnn.com/2022/08/16/politics/liz-cheney-wyoming-alaska-primaries/index.html
Upvotes: 1
Reputation: 21
If your url (and the view) contains variable office
then you can pass it like this:
{% url 'some-url-name' foobar %}
or like this, if you have more than one parameter:
{% url 'some-url-name' office='foobar' %}
Documentation: https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#url
Upvotes: 2
Reputation: 383580
Use urlencode
if the argument is a variable
<a href="{% url 'myview' %}?office={{ some_var | urlencode }}">
or else special characters like spaces might break your URL.
Documentation: https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#urlencode
Upvotes: 40
Reputation: 115
Try this:
{% url 'myview' office=foobar %}
It worked for me. It basically does a reverse on that link and applies the given arguments.
Upvotes: 0
Reputation: 3514
A way to mix-up current parameters with new one:
{% url 'order_list' %}?office=foobar&{{ request.GET.urlencode }}
Modify your settings to have request variable:
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
Upvotes: 47
Reputation: 599758
No, because the GET parameters are not part of the URL.
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
Upvotes: 226
Reputation: 7328
First, a silly answer:
{% url my-view-name %}?office=foobar
A serious anwser: No, you can't. Django's URL resolver matches only the path part of the URL, thus the {% url %}
tag can only reverse that part of URL.
Upvotes: 9