我正在尝试对基于类的视图进行分页。以下是我的观点:
class IssuesByTitleView(ListView):
context_object_name = "issue_list"
def issues(request):
issue_list = Issue.objects.all()
###### Commented out does not work ######
# paginator = Paginator(issue_list, 24)
# try:
# page = int(request.GET.get('page', '1'))
# except ValueError:
# page = 1
# try:
# issues = paginator.page(page)
# except (EmptyPage, InvalidPage):
# issues = paginator.page(paginator.num_pages)
def get_queryset(self):
self.title = get_object_or_404(Title, slug=self.kwargs['title_slug'])
return Issue.objects.filter(title=self.title).order_by('-number')
def get_context_data(self, **kwargs):
context = super(IssuesByTitleView, self).get_context_data(**kwargs)
context['title'] = self.title
return context
以下是我的模型的一些示例:
class Title(models.Model):
CATEGORY_CHOICES = (
('Ongoing', 'Ongoing'),
('Ongoing - Canceled', 'Ongoing - Canceled'),
('Limited Series', 'Limited Series'),
('One-shot', 'One-shot'),
('Other', 'Other'),
)
title = models.CharField(max_length=64)
vol = models.IntegerField(blank=True, null=True, max_length=3)
year = models.CharField(blank=True, null=True, max_length=20, help_text="Ex) 1980 - present, 1980 - 1989.")
category = models.CharField(max_length=30, choices=CATEGORY_CHOICES)
is_current = models.BooleanField(help_text="Check if the title is being published where Emma makes regular appearances.")
slug = models.SlugField()
class Meta:
ordering = ['title']
def get_absolute_url(self):
return "/titles/%s" % self.slug
def __unicode__(self):
class Issue(models.Model):
title = models.ForeignKey(Title)
number = models.CharField(max_length=20, help_text="Do not include the '#'.")
...
当然,通过遵循Django文档,当View由以下内容定义时,分页系统会起作用:def view(request):
我也想知道如何取出下一个和之前的对象。
我需要一个指向“下一期(带有名称和发行号码的上下文)”的链接,然后是“上一期”链接。请注意,只需使用下一个或上一个问题更改模板链接就无法运行。
所以,如果有人能帮助我,那就太好了。
答案 0 :(得分:15)
只需将paginate_by = 20
添加到您的观看类。
class IssuesByTitleView(ListView):
context_object_name = "issue_list"
paginate_by = 20
#More stuff here..
答案 1 :(得分:1)
就像Evan Porter所评论的那样,您可以使用page_obj
上下文变量来访问number, paginatior.num_pages, has_next, has_previous
。从Django 1.4.1升级到1.7,KeyError['page']
object_list to ListView
救了我的东西