Django过滤器如何从FilterSet中的视图传递当前用户?

时间:2017-12-05 05:50:02

标签: python django django-filters

我有一个过滤器,我需要访问request.user。但是,Django-filter没有通过它。我能够找出可能的FilterSet配置。 但是如何从FilterSet中的视图传递当前用户?

filters.py

class TransationsListFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')
    super(TransationsListFilter, self).__init__(*args, **kwargs)

    transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs {'placeholder': 'DD/MM/YYYY'}))
    class Meta:
        model = Transations
        fields = ['transaction_date']

    @property
        def qs(self):
        return super(TransationsListFilter, self).filter(user=user)

views.py

class TransactionsList(PagedFilteredTableView):
    model = Transations
    table_class = TransactionsTable
    filter_class = TransationsListFilter
    formhelper_class = TransationsFormHelper

models.py

class Transations(models.Model):
    transaction_date = models.DateField(default=datetime.now, blank=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        default = 0
   )

1 个答案:

答案 0 :(得分:0)

我用 django-crum 插件解决了我的问题。  这是我的最终代码(其他文件是相同的):
filters.py

import django_filters
from django_filters import DateFromToRangeFilter
from django_filters.widgets import RangeWidget
from .models import Transations,Account
from crum import get_current_user

class TransationsListFilter(django_filters.FilterSet):
    transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs={'placeholder': 'DD/MM/YYYY'}))
    class Meta:
        model = Transations
        fields = ['transaction_date']

    @property
    def qs(self):
        parent = super(TransationsListFilter, self).qs
        return parent.filter(user=get_current_user())