gpt4 book ai didi

python - 如何将当前用户传递给 Django_filters ModelChoiceFilter 查询集

转载 作者:行者123 更新时间:2023-12-04 10:33:28 26 4
gpt4 key购买 nike

如何将当前用户传递给 Django_filters ModelChoiceFilter查询集。

我正在尝试过滤 ModelChoiceFilter基于当前用户,我使用了 init过滤器中的方法,但失败了:

这是我使用的代码:

View .py

def requests_reports(request):
f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user), user=request.user)
context = {
'filter': f,
}
return render(request, 'requests_reports.html', context)

forms.py

class RequestsFilter(django_filters.FilterSet):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(RequestsFilter, self).__init__(*args, **kwargs)
self.fields['employee'].queryset = Employee.objects.filter(user=self.user)

start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))

class Meta:
model = LeaveRequest
fields = ['employee', 'type']

它返回此错误:
'RequestsFilter' object has no attribute 'fields'

最佳答案

使用正常 _init_但不是 self.fields['field_name]使用 self.filters[field_name]
试试这个代码:

class RequestsFilter(django_filters.FilterSet):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super().__init__(*args, **kwargs)
self.filters['employee'].queryset = Employee.objects.filter(user=self.user)
start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))
employee = django_filters.ModelChoiceFilter(queryset=None, field_name='employee' )
class Meta:
model = LeaveRequest
fields = ['employee', 'type', 'date_time']

关于python - 如何将当前用户传递给 Django_filters ModelChoiceFilter 查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60302773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com