简体   繁体   中英

LoginRequiredMixin and get_queryset with django-tables2

I already had a working table built on Django's generic ListView class. But I was missing the ability to sort and I therefore took a look at generating a new table using django-tables2. It was very easy to set up, but I don't know how to implement two important features from my old ListView class; 1) page is only visible to logged in users and 2) filter objects based on user.

Here is my old class in 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)

Here is the new django-tables2 function in views.py :

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

and the new 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',)

How do I implement LoginRequiredMixin (so that the list page is only visible to logged in users) and my old get_queryset (so that user only see the cars they are supposed to see) with django-tables2? Can anyone help. Thank you very much for any assistance!

For managing permission to view page you can still use login_required decorator for your function-based views.

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})

And you should put correct filtered queryset when initializing CarTable.

For filtering objects, you can pass the filtered QuerySet to the table rather than 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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM