Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass query parameters via Django's {% url %} template tag?

People also ask

What does form {% URL %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

What does the built in Django template tag URL do?

The URL template tag is a typical type of Tag in the Django Template Language framework. This tag is specifically used to add View URLs in the Template Files.


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">

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',
)

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


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.


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