Carrying parameters when django uses paginate for paging

created at 07-16-2021 views: 1

In django, when using paging, the paging URL needs to carry parameters, such as:

http://127.0.0.1:8000/admin/people.html?page=1&dynasty=%E4%B8%A4%E6%B1%89

When I turned the second page, when I used the get request, I found that there were no parameters in the URL. I want the URL that appears when I click on the link on the next page:

http://127.0.0.1:8000/admin/people.html?page=2&dynasty=%E4%B8%A4%E6%B1%89

Actually, when I use the get request, I only get the page parameter in the end, and none of the other parameters are carried.

http://127.0.0.1:8000/admin/people.html?page=2

Solution

views.py

from urllib.parse import urlencode
from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def url_replace(context, next_page):
    if query.startswith('page') or not len(query):
        new_url = f'page={next_page}'
    elif '&page=' in query:
        get_params = query.rpartition('&page=')[0] # equivalent to .split('page='), except more efficient 
        new_url = f'{get_params}&page={next_page}'
    else:
        new_url = f'{query}&page={next_page}'
    return new_url

html

<a href="?{% url_replace page=paginator.next_page_number %}">
Please log in to leave a comment.