我如何通过"请求"到ListView使用" paginate_by"作为变量?
我找到了很多像这样的例子:
class CarListView(ListView):
model = models.Car
template_name = 'app/car_list.html'
context_object_name = "car_list"
paginate_by = 10
我想从我的用户设置模型中获取paginate_by变量" UserSettings"
我已经厌倦了以下方式使用它:
class CarListView(ListView):
model = models.Car
template_name = 'app/car_list.html'
context_object_name = "car_list"
user_settings = UserSettings.objects.get(user=request.user.id)
paginate_by = user_settings.per_page
但我有错误"姓名'请求'未定义"
答案 0 :(得分:2)
您可以添加方法get_paginate_by()
来执行您需要的操作并使用来自self.request
的请求。
示例代码为
class CarListView(ListView):
...
def get_paginate_by(queryset):
user_settings = UserSettings.objects.get(user=self.request.user.id)
return user_settings.per_page
妥善处理错误情况。
答案 1 :(得分:0)
为了安全回退:
class CarListView(ListView):
model = models.Car
template_name = 'app/car_list.html'
context_object_name = "car_list"
paginate_by = 10
user_settings = UserSettings
def get_paginate_by(self, queryset):
"""
Try to fetch pagination by user settings,
If there is none fallback to the original.
"""
try:
self.paginate_by = self.user_settings.objects.get(user=self.request.user.id).per_page
except:
pass
return self.paginate_by
或者如果您想在不同的视图中使用它,请创建一个Mixin:
class UserPagination(object):
def get_paginate_by(self, queryset):
"""
Try to fetch pagination by user settings,
If there is none fallback to the original.
"""
try:
self.paginate_by = self.user_settings.objects.get(user=self.request.user.id).per_page
except:
pass
return self.paginate_by
然后:
class CarListView(UserPagination, ListView):
model = models.Car
template_name = 'app/car_list.html'
context_object_name = "car_list"
paginate_by = 10
user_settings = UserSettings