Menu
CoddyTech

Keeping the Filter

Part of the Class-Based Views section of Coddy's Django journey. Lesson 9 of 18.

Open the Berlin jobs and press Next: page 2 lists jobs from every city. The link is ?page=2, a whole new query string, so city=Berlin is gone.

The tag {% querystring %} starts from the current query string, sets the values you name, and writes the result, ? included. It is built in since Django 5.1, so it needs no {% load %}. A recipe list filtered by cuisine links to a sorted view:

<a href="{% querystring sort="minutes" %}">Quickest first</a>

On /recipes/?cuisine=thai that writes ?cuisine=thai&sort=minutes: the filter survives. A value can be a template variable, and None removes a key: {% querystring sort="minutes" page=None %} also goes back to page 1.

Write no ? before the tag, or the link starts with ??.

challenge icon

Challenge

Easy

In job_list.html, make both pagination links keep the rest of the query string:

  • Next on /jobs/?city=Berlin goes to ?city=Berlin&page=2.
  • Previous keeps the city too.
  • On /jobs/, Next still goes to ?page=2.

Press Run and press Next on the Berlin jobs.

Try it yourself

{% extends "jobs/base.html" %}

{% block title %}Jobs{% endblock %}

{% block content %}
  <h1>Jobs</h1>
  <p class="cities">
    <a href="{% url 'jobs:list' %}">All cities</a>
    <a href="?city=Berlin">Berlin</a>
    <a href="?city=Lisbon">Lisbon</a>
    <a href="?city=London">London</a>
  </p>
  <ul class="jobs">
    {% for job in jobs %}
      <li class="job">
        <a href="{% url 'jobs:detail' job.slug %}"><strong>{{ job.title }}</strong></a>
        at {{ job.company }}, {{ job.city }}
      </li>
    {% empty %}
      <li>No jobs yet.</li>
    {% endfor %}
  </ul>

  {% if is_paginated %}
    <nav class="pages">
      {% if page_obj.has_previous %}
        <a href="?page={{ page_obj.previous_page_number }}">Previous</a>
      {% endif %}
      <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>
      {% if page_obj.has_next %}
        <a href="?page={{ page_obj.next_page_number }}">Next</a>
      {% endif %}
    </nav>
  {% endif %}
{% endblock %}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Class-Based Views

Practice on your own: Django playground