1

When i search for something(like tom), it works well for first page. But if I click next page url, it shows the same result, nothing changes, but in url, it becomes http://127.0.0.1:8000/search/?caption=tom to http://127.0.0.1:8000/search/?caption=tom&?page=2

filters.py:

class VideoFilter(django_filters.FilterSet):
    class Meta:
        model = Video
        fields = ['caption']
        filter_overrides = {
             models.CharField: {
                 'filter_class': django_filters.CharFilter,
                 'extra': lambda f: {
                     'lookup_expr': 'icontains',
                 },
             },
         }

views.py:

def search(request):
    queryset = Video.objects.all()
    filterset = VideoFilter(request.GET, queryset=queryset)
    if filterset.is_valid():
        queryset = filterset.qs

    paginator = Paginator(queryset, 2)
    page_number = request.GET.get('page')
    print(page_number)# always prints **none**
    queryset = paginator.get_page(page_number)
    
    return render(request, 'search.html',{
        'result': queryset,
        'caption': request.GET['caption'],
    })

search.html:

{% extends 'navbar.html' %}
{% block body %}

<!-- more code -->
{% if result.has_next %}
    <a href="?caption={{caption}}&?page={{result.next_page_number}}"><button>See more results</button></a>
{% endif %}

{% endblock body %}

navbar.html:

<!-- more code -->
<form action="/search/" method="GET"> <!-- working without csrf_token -->
            <input type="text" placeholder="Search" id="search" name="caption" required />
            <button type="submit">Search</button>
        </form>

where is the problem? how do i visit next page?

Asif Biswas
  • 161
  • 2
  • 9

1 Answers1

2

You made an error in the URL of the button, the key-value pairs in the query string [wiki] are separated by an ampersand (&), not an ampersand with question mark (&?). By writing it that way, Django will interpret this as:

>>> QueryDict('caption=tom&?page=2')
<QueryDict: {'caption': ['tom'], '?page': ['2']}>

so then the parameter is not page, but ?page.

We can fix this by removing the question mark between the caption and the page in the URL:

<a href="?caption={{ caption|urlencode }}&page={{ result.next_page_number }}">

You should also use the |urlencode template filter [Django-doc] to prevent a wrong querystring, for example when the caption would have a questionmark, number sign (#), etc. The |urlencode filter will transform the text in percent encoding [wiki].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555