How it works...

All the three created template tags behave similarly. At first, they read the current query parameters from the request.GET dictionary-like QueryDict object to a new list of (key, value) query_params tuples. Then, the values are updated depending on the positional arguments and keyword arguments. Lastly, the new query string is formed via the helper method defined first. In this process, all spaces and special characters are URL-encoded, and the ampersands connecting the query parameters are escaped. This new query string is returned to the template.

To read more about the QueryDict objects, refer to the official Django documentation at https://docs.djangoproject.com/en/2.1/ref/request-response/#querydict-objects.

Let's take a look at an example of how the {% modify_query %} template tag can be used. Positional arguments in the template tag define which query parameters are to be removed, and the keyword arguments define which query parameters are to be updated in the current query. If the current URL is http://127.0.0.1:8000/artists/?category=fine-art&page=5, we can use the following template tag to render a link that goes to the next page:

{% load utility_tags %} 
<a href="{% modify_query page=6 %}">6</a>

The following snippet is the output rendered using the preceding template tag:

<a href="/artists/?category=fine-art&amp;page=6">6</a> 

We can also use the following example to render a link that resets pagination and goes to another category, sculpture, as follows:

{% load utility_tags %} 
<a href="{% modify_query "page" category="sculpture" %}">
Sculpture</a>

So, the rendered output rendered using the preceding template tag would be as shown in this snippet:

<a href="/artists/?category=sculpture">
Sculpture</a>

With the {% add_to_query %} template tag, you can add parameters step-by-step with the same name. For example, if the current URL is http://127.0.0.1:8000/artists/?category=fine-art, you can add another category, Sculpture, with the help of the following snippet:

{% load utility_tags %} 
<a href="{% add_to_query category="sculpture" %}">
+ Sculpture</a>

This will be rendered in the template, as shown in the following snippet:

<a href="/artists/?category=fine-art&amp;category=sculpture">
+ Sculpture</a>

Lastly, with the help of the {% remove_from_query %} template tag, you can remove the parameters step-by-step with the same name. For example, if the current URL is http://127.0.0.1:8000/artists/?category=fine-art&category=sculpture, you can remove the Sculpture category with the help of the following snippet:

{% load utility_tags %} 
<a href="{% remove_from_query category="sculpture" %}">
- Sculpture</a>

This will be rendered in the template as follows:

<a href="/artists/?category=fine-art">
- Sculpture</a>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.243.32