如何将当前登录的用户传递给 filter.py 即 django 中基于请求的过滤

How to pass currently logged in user to filter.py i.e request based Filtering in django

我想限制每个用户的视图,即用户只能查看与其相关的帐户详细信息。

为此,我创建了一个过滤器,我想在其中传递登录用户的详细信息。

下面是filter.py

的截图
class networkFilterUserbased(django_filters.FilterSet):

def __init__(self, *args, **kwargs):
    super().__init__(*args,**kwargs)

    request = kwargs['request']
    username = request.user.id

    my_choices = NetworkRelatedInformation.objects.values_list('account', 'account__accountName') \
    .filter(account__accountusermapping__userId=username).distinct()

    self.filters['account'].extra.update({'choices': my_choices})

class Meta:
    model = NetworkRelatedInformation
    fields = ['month', 'year', 'account']

我在 views.py

中使用这个过滤器
def UserSpecificDashBoardView(request, *args, **kwargs):
    month = request.GET.get('month')
    year = request.GET.get('year')
    account = request.GET.get('account')

   ......All Logic here....



   network_list_user = NetworkRelatedInformation.objects.all()
   network_filter_user = networkFilterUserbased(request.GET, queryset=network_list_user)
   return render(request, 'personal/dashboardnew.html', {'filter': network_filter_user})

现在的问题是,当我将上面示例中的用户用户名等硬编码值作为 uername1 传递时,它工作正常,但是有 100 多个用户,所以我想直接从请求传递值。

意味着当我传递 request.user 代替用户名时它不起作用。

我尝试了多种使用基于请求的过滤的解决方案,但没有任何效果。请告知我如何将当前登录的用户值传递给上述过滤器。

models.py

class AccountInformation(models.Model):
    accountName = models.CharField(max_length=40)
    countryName = models.CharField(max_length=40)
    managerName = models.CharField(max_length=40)
    location = models.CharField(max_length=40)

class AccountUserMapping(models.Model):
    accountId = models.ForeignKey('AccountInformation', on_delete=models.DO_NOTHING)
    userId = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='%(class)s_requests_created')


class NetworkRelatedInformation(models.Model):
    MONTH_CHOICES = [(str(i), calendar.month_name[i]) for i in range(1, 13)]

    account = models.ForeignKey('AccountInformation', on_delete=models.DO_NOTHING)
    month = models.CharField(max_length=9, choices=MONTH_CHOICES, default='1')
    year = models.IntegerField(default=0)

    alarm_count = models.IntegerField(default=0)
    tt_count = models.IntegerField(default=0)
    cr_count = models.IntegerField(default=0)
    wo_count = models.IntegerField(default=0)
    subs_count = models.IntegerField(default=0)

问题出在filter.py我无法得到request.user

Trace back
Traceback (most recent call last):
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\esacjak\Desktop\Code Backup\operatewebportal\personal\views\account.py", line 4917, in UserSpecificDashBoardView
'totalsrfothersheadcount': totalsrfothersheadcount
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\shortcuts.py", line 36, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 175, in render
return self._render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 943, in render
bit = node.render_annotated(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 910, in render_annotated
return self.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader_tags.py", line 155, in render
return compiled_parent._render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 943, in render
bit = node.render_annotated(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 910, in render_annotated
return self.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\defaulttags.py", line 314, in render
return nodelist.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 943, in render
bit = node.render_annotated(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 910, in render_annotated
return self.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader_tags.py", line 67, in render
result = block.nodelist.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 943, in render
bit = node.render_annotated(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 910, in render_annotated
return self.render(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\widget_tweaks\templatetags\widget_tweaks.py", line 176, in render
bounded_field = self.field.resolve(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 676, in resolve
obj = self.var.resolve(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 802, in resolve
value = self._resolve_lookup(context)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\base.py", line 843, in _resolve_lookup
current = getattr(current, bit)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django_filters\filterset.py", line 231, in form
for name, filter_ in six.iteritems(self.filters)])
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django_filters\filterset.py", line 231, in <listcomp>
for name, filter_ in six.iteritems(self.filters)])
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django_filters\filters.py", line 406, in field
return super(QuerySetRequestMixin, self).field
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django_filters\filters.py", line 199, in field
self._field = self.field_class(label=self.label, **field_kwargs)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django_filters\fields.py", line 237, in __init__
super(ChoiceIteratorMixin, self).__init__(*args, **kwargs)
File "C:\Users\esacjak\AppData\Local\Programs\Python\Python36\lib\site-packages\django\forms\models.py", line 1173, in __init__
initial=initial, help_text=help_text, **kwargs
TypeError: __init__() got an unexpected keyword argument 'choices'
[11/Jul/2018 22:08:50] "GET /personal/dashboardnew/ HTTP/1.1" 500 301865

你检查过FilterSet的构造函数了吗?它看起来像这样:

def __init__(self, data=None, queryset=None, prefix=None, strict=None, request=None):
   pass

所以我相信,如果你正确地实例化你的过滤器,你可以在你的过滤器中访问当前请求,你应该能够访问 request.user。

network_filter_user = networkFilterUserbased(queryset=network_list_user, request=request)   

更新

在你改变我提到的东西之后。您可以在过滤器的初始化方法中更新过滤器的选择:

class networkFilterUserbased(django_filters.FilterSet):

    account = django_filters.ChoiceFilter(choices=None)

    class Meta:
        model = ** model **
        fields = ['account', ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args,**kwargs)

        request = kwargs['request']          
        if request.user.is_authenticated:
            username = request.user.username
            my_choices = ** build your choices here**  
            self.filters['account'].extra.update( { 'choices' : my_choices })

注意:我无法验证您的查询以获取您想要的选项列表,因为我没有相同的数据库。所以这取决于你是否正确。

如何在 Filters.py 文件 Django

中获取当前登录用户

在我的例子中,我想要团队负责人,基于当前登录的用户(经理)。 为此,我有 Views.py 文件和 filters.py 文件。

filters.py 文件代码:

class FeedbackSearchFilterManager(django_filters.FilterSet):

task__team_lead = django_filters.ModelChoiceFilter(name='task__team_lead', label='Team Lead', empty_label="---select expert----",
                                          widget=forms.Select(attrs={'class': 'form-control'}), queryset=None)

class Meta:
    model = Feedback
    fields = ['search', 'status',]

# this method for getting current logged in user in filter.py file
def __init__(self, *args, **kwargs):
    super(FeedbackSearchFilterManager,self).__init__(*args, **kwargs)
    request = kwargs['request']
    if request.user.is_authenticated:
        username = request.user.id
        userlocation = request.user.location_id
        self.filters['task__team_lead'].queryset = UserAccount.objects.filter(manager_id=username, location=userlocation)

在该文件中,def init() 方法将 return 您当前登录的用户。 正如您在我的 task__team_lead 模型选择过滤器中看到的,我传递了一个属性

nametask__team_lead" >> 这是一个外键关系 bcz 在反馈模型中没有提交 team_lead 模型,但在任​​务模型中我们有 team_lead 字段以及任务和反馈table 连接外键

当我以经理身份登录时,我正在获取团队负责人列表(基于经理和经理位置,团队负责人位置相同)。