Search code examples
pythondjangodjango-pagination

Django Pagination with other variables in the GET request in a Function Based View


I've tried to implement the following solution from here: How to paginate Django with other get variables?

I added this to my views.py

from urllib.parse import urlencode
from django import template
register = template.Library()

@register.simple_tag
def url_replace(request, field, value):

    dict_ = request.GET.copy()

    dict_[field] = value

    return dict_.urlencode()

def teacher_list(request, **kwargs):
    paginator = Paginator(results, 1)
    page = request.GET.get('page')

    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        results = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        results = paginator.page(paginator.num_pages)

template.html

{% if teacher_list.has_next %}
<li><a href="?{% url_replace request 'page' teacher_list.next_page_number %}">Next</a></li>
{% endif %}

However, this gives me: Invalid block tag on line 155: 'url_replace', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?

I also tried loading:

@register.simple_tag(takes_context=True)
def url_replace(context, **kwargs):
    query = context['request'].GET.dict()
    query.update(kwargs)
    return urlencode(query)

without success. I also tried:

@register.simple_tag(takes_context=True)
def url_replace(request, **kwargs):
    query = request.GET.dict()
    query.update(kwargs)
    return urlencode(query)

None of these seem to work.


Solution

  • Django could not to load your tag

    by docs custom-template-tags

    you need add templatetags (change your_app and your_tags on your valid values):

    your_app/
        __init__.py
        models.py
        templatetags/
            __init__.py
            your_tags.py
    

    in the template load your tags

    {% load your_tags %}