簡體   English   中英

LoginRequiredMixin 和 get_queryset 與 django-tables2

[英]LoginRequiredMixin and get_queryset with django-tables2

我已經有一個基於 Django 的通用 ListView 類構建的工作表。 但是我缺少排序的能力,因此我研究了使用 django-tables2 生成一個新表。 設置起來非常容易,但我不知道如何從我的舊 ListView 類中實現兩個重要功能; 1) 頁面僅對登錄用戶可見,2) 基於用戶過濾對象。

這是我在views.py舊課程:

class CarList(LoginRequiredMixin, ListView):
    model = Car
    paginate_by = 20

def get_queryset(self):
    qs = super().get_queryset()
    return qs if self.request.user.is_staff else qs.filter(bureau=self.request.user.bureau, active = 1)

這是views.py的新 django-tables2 函數:

def car(request):
    table = CarTable(Car.objects.all())
    RequestConfig(request, paginate={'per_page': 25}).configure(table)
    return render(request, 'car.html', {'table': table})

和新的tables.py

import django_tables2 as tables
from app.models import Feriehus
from django.contrib.auth.mixins import LoginRequiredMixin

class CarTable(tables.Table):
    class Meta:
        model = Car
        attrs = {'class': 'paleblue'}
        fields = ('car_id', 'type', 'price', 'year',)

我如何使用 django-tables2 實現 LoginRequiredMixin(以便列表頁面僅對登錄用戶可見)和我的舊 get_queryset(以便用戶只能看到他們應該看到的汽車)? 任何人都可以幫忙。 非常感謝您的任何幫助!

為了管理查看頁面的權限,您仍然可以為基於函數的視圖使用login_required裝飾器。

from django.contrib.auth.decorators import login_required    


@login_required
def car(request):
    table = CarTable(Car.objects.all())
    RequestConfig(request, paginate={'per_page': 25}).configure(table)
    return render(request, 'car.html', {'table': table})

並且您應該在初始化 CarTable 時放置正確的過濾查詢集。

對於過濾對象,您可以將過濾后的 QuerySet 傳遞給表而不是all

def car(request):
    cars = Car.objects.all()
    # filter the objects
    if not request.user.is_staff:
        cars = cars.filter(bureau=request.user.bureau, active = 1)
    table = CarTable(cars)
    RequestConfig(request, paginate={'per_page': 25}).configure(table)
    return render(request, 'car.html', {'table': table})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM