基于函数的视图中 GET 请求中的 Django 分页和其他变量

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

我尝试从这里实施以下解决方案: How to paginate Django with other get variables?

我将此添加到我的 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?

我也试过加载:

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

没有成功。我也试过:

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

None 这些似乎有效。

Django 无法加载您的标签

通过文档 custom-template-tags

您需要添加 templatetags(更改 your_appyour_tags 您的有效值):

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

在模板中加载您的标签

{% load your_tags %}