【问题标题】:Django how to allow user to set paginate_by value in profileDjango 如何允许用户在配置文件中设置 paginate_by 值
【发布时间】:2020-03-31 00:32:28
【问题描述】:

我允许我的用户更新他们的个人资料并为各种 ListView 页面设置 paginate_by 值。如何在我的视图中访问此值?目前,默认为 20,如图所示:

class CandidateListView(LoginRequiredMixin, ListView):
    template_name = 'recruiter/candidate_list.html'
    context_object_name = 'candidates'
    paginate_by = 20

我想访问他们个人资料中的那个字段,而不是 20 个。我是否需要将其作为参数传递给查看?谢谢。

【问题讨论】:

    标签: django pagination


    【解决方案1】:

    如果用户有一个相关的Profile模型,带有一个字段,例如:

    from django.conf import settings
    
    class Profile(models.Model):
        user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        paginate_by = models.PositiveIntegerField(default=10)
        # …

    您可以覆盖.get_paginate_by(..) method [Django-doc]:

    class CandidateListView(LoginRequiredMixin, ListView):
        template_name = 'recruiter/candidate_list.html'
        context_object_name = 'candidates'
    
        def get_paginate_by(self, queryset):
            return self.request.user.profile.paginate_by

    如果.profile 不存在,将try-except 包装起来可能更安全:

    class CandidateListView(LoginRequiredMixin, ListView):
        template_name = 'recruiter/candidate_list.html'
        context_object_name = 'candidates'
        paginate_by = 20
    
        def get_paginate_by(self, queryset):
            try:
                return self.request.user.profile.paginate_by
            except Profile.DoesNotExist:
                return super().get_paginate_by(queryset)

    当该用户的个人资料不存在时,您将回退到 20

    如果不想对结果进行分页,可以返回None

    【讨论】:

    • 完美。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 2010-11-11
    • 2014-10-28
    • 2022-01-10
    • 2019-04-01
    • 2012-05-09
    相关资源
    最近更新 更多