Home > Mobile >  User selected number of objects per page in Django
User selected number of objects per page in Django

Time:08-31

I made pagination for my site but I want to let the user choose how many records are displayed at one time e.g. 10, 15, 25. This is my views.py

def finished_ads_view(request):
    queryset = Campaign.objects.filter(completion_percent=100)

    try:
        per_page = request.GET['dropdown']
    except:
        per_page = 1

    page = request.GET.get('page', 1)
    paginator = Paginator(queryset, per_page)

    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    context = {
        'posts': posts,
    }

    return render(request, 'finished_campaigns.html', context)

And this is part of my template:

<select name="dropdown">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="15">15</option>
    <option value="20">20</option>
</select>
<input type="submit" value="Submit"/>

The problem is that the dropdown value does not change and the number of records displayed at one time is still the same as the except: per_page value.

CodePudding user response:

You should wrap your select and submit in a form so the value gets passed to the backend in query string.

<form method="get">
    <input type="hidden" name="page" value="{{ page }}">
    ...
</form>

Also pagination parameter needs to be included so I added that. You need to add it to the context as well. Then when creating links for the pages with GET attribute don't forget to pass the dropdown as well.

CodePudding user response:

To see the whole template can be better. I can only imagine:

<form>
<-- any staff here -->
    <input type="hidden" name="page" value="{{ request.GET.page }}">
<-- any staff here -->
<select name="dropdown">
    <option {% if request.GET.dropdown == "1" %}selected{% endif %} 
 value="1">1</option>
    <option {% if request.GET.dropdown == "2" %}selected{% endif %} 
 value="2">2</option>
    <option {% if request.GET.dropdown == "15" %}selected{% endif %} value="15">15</option>
    <option {% if request.GET.dropdown == "20" %}selected{% endif %} value="20">20</option>
</select>
<-- any staff here -->
<input type="submit" />
<-- any staff here -->
</form>

Dont forget to add request in context, if you don't have request context processor.

  • Related