0

I have the following view that gets and paginates search results:

def search(request):

    query=request.GET.get('q','')

    form=SearchForm({'q': query })

    results = form.search()

    paginator = Paginator(results, 15)

    print 'page is: '+request.GET.get('page')

    try:
        page = paginator.page(int(request.GET.get('page')))
    except InvalidPage:
        raise Http404("No such page of results!")

    for result in page.object_list:
        print result.object.name
    #this prints the same every time!




    context = {
        'view':resolve(request.path_info).url_name,
        'form':form,
        'page':page,
        'query':query,
    }

    return render(request, 'nutrition/food-log.html', context)

My template looks like the following:

{% if query %}
            <h3>Results</h3>

            {% for result in page.object_list %}
                <p>{{ result.object.name }}</p>
            {% empty %}
                <p>No results found.</p>
            {% endfor %}

            {% if page.has_previous or page.has_next %}
                <div>
                    {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %}
                    |
                    {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %}
                </div>
            {% endif %}
        {% else %}
            {# Show some example queries to run, maybe query syntax, something else? #}
        {% endif %}

Does anyone know why this is happening?

Atma
  • 29,141
  • 56
  • 198
  • 299
  • You're GET may not be successfully grabbing the `page` field, and be defaulting to `1` instead. You should test it with a print statement or some such. – Johndt Aug 22 '14 at 17:05
  • i tried that and changed the example above, the page prints accordingly. – Atma Aug 22 '14 at 17:29
  • [Note here](https://docs.djangoproject.com/en/1.6/topics/pagination/#using-paginator-in-a-view) that you can access the objects in the page by simply iterating through the page: `{% for result in page %}`. Don't think this would make a difference though. – Johndt Aug 22 '14 at 17:38
  • Could you also print in your view the length of `results`? – AdelaN Aug 22 '14 at 18:35
  • This link may help you :[Link](https://stackoverflow.com/questions/63506609/how-organize-pagination-with-a-large-number-of-pages-in-django-project/63507365#63507365) – Riyas Ac Sep 01 '20 at 17:16

0 Answers0