Reputation: 99
I have pagination, html:
{% extends 'base.html' %}
{% load pagination_tags %}
{% block title %}NewsLine{% endblock title %}
{% load humanize %}
{% block content %}
{% autopaginate news news_on_page %}
{% paginate %}
News on page:
<input type="submit" value="10" />
<input type="submit" value="20" />
<input type="submit" value="50" />
<div class="container mt-3">
<div class="row my-5">
<div class="col-11">
<p>News overall {{ paginator.count }}</p>
<p>Number of pages {{ paginator.num_pages }}</p>
<p>Page range {{ paginator.page_range }}</p>
{% for peace_of_news in news %}
<div class="p-3">
<h2>{{ peace_of_news.title }}</h2>
<p><small>{{ peace_of_news.date|naturaltime }}</small></p>
<p>{{ peace_of_news.text }}</p>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock content %}
views.py:
from django.shortcuts import render
from . models import PieceOfNews
from django.core.paginator import Paginator
from django import forms
def index(request):
news = PieceOfNews.objects.all().order_by('-date')
paginator = Paginator(news, 10)
all = list(PieceOfNews.objects.all())
news_on_page = 3
context = {'news': news, 'paginator': paginator, 'all': all, 'news_on_page': news_on_page}
class Meta:
verbose_name_plural = 'piece of news'
return render(request, 'index.html', context)
def get_value():
news_on_page = forms.IntegerField()
How to get some value via button to adjust number of news on page
For example, user have choices: 10 news per page, 20 news per page and 50 news per page.
How to send this value in html form or in views to return it value again in template?
OR
Maybe there are some better way
to do pagination which user can adjust?
Upvotes: 0
Views: 206
Reputation: 1673
You can try this:
Use the button values to change the location by passing the limit
query through the URL.
News on page:
<input type="submit" value="?limit=10" onclick="location = this.value;"/>
<input type="submit" value="?limit=20" onclick="location = this.value;"/>
<input type="submit" value="?limit=50" onclick="location = this.value;"/>
Read the limit query from the URL in the index view function and paginate the results with that value.
def index(request):
# Read the limit query
limit = request.GET.get('limit', 10)
news = PieceOfNews.objects.all().order_by('-date')
# Use the limit in the paginator
paginator = Paginator(news, limit)
all = list(PieceOfNews.objects.all())
news_on_page = 3
context = {'news': news, 'paginator': paginator, 'all': all, 'news_on_page': news_on_page}
class Meta:
verbose_name_plural = 'piece of news'
return render(request, 'index.html', context)
Note : If the limit
query string is not found then the default limit will be 10.
Upvotes: 1