[Answer]-Django 1.4 Pagination with a query

1👍

from django.core.paginator import Paginator, InvalidPage, EmptyPage

def search(request):
    found_entries = inventory.objects.filter()

    if request.GET.get('q'):
        query_string = request.GET.get('q')
        found_entries = found_entries.filter(
                id__icontains=query_string
            ).filter(
                address__icontains=query_string
            ).filter(
                itemcode__icontains=query_string
            ).filter(
                qty__icontains=query_string
            ).filter(
                description__icontains=query_string
            ).filter(
                metatags__icontains=query_string
            ).order_by('-qty')

    paginator = Paginator(found_entries, 10) # Show 10 items per page

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        found_entries = paginator.page(page)
    except (EmptyPage, InvalidPage):
        found_entries = paginator.page(paginator.num_pages)

    return render_to_response('dynamite_frontpage.html', {
        "found_entries": found_entries,
    })

In your template:

<input name="q" type="text" value="{{ request.GET.q }}">

Template tag test:

<form class="form-searchbar" method='get' action='/search/'>
    <input name="q" type="text" value="{{ request.GET.q }}">
</form>

Leave a comment