如何将当前登录的用户传递给filter.py,即在Django中基于请求的过滤 [英] How to pass currently logged in user to filter.py i.e request based Filtering in django

查看:61
本文介绍了如何将当前登录的用户传递给filter.py,即在Django中基于请求的过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to restrict the views for each user i.e a user can view only those account details that are related to him only.

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

For this i have created a Filter where i want to pass the Logged in User details.

下面是filter.py的快照

Below is the snapshot of 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

And i am using this filter in my 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个用户,所以我想直接从请求中传递值。

Now the problem is when i am passing hardcoded values like username of the user in above example as uername1 it is working fine, But there are 100s of users so i want to pass the value directly from request.

是指我在传递request.user而不是用户名时不起作用。

Means when i am passing request.user in place of username it is not working.

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

I tried multiple solutions using request based filtering but nothing works. Pls advise how can i pass the currently logged in user value to the above filter.

models.py

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

Problem is in filter.py i am not able to get 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?看起来像这样:

Have you checked the constructor of FilterSet? It looks like this:

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

因此,我相信,如果您正确地实例化了过滤器,您可以在过滤器中访问当前请求,并且应该可以访问request.user。

So I believe, if you properly instantiate your filter, you can access current request in your filter and you should be able to access request.user.

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

更新

在您更改我提到的内容之后。您可以在过滤器的init方法中更新过滤器的选择:

AFter you change the thing i mentioned. you can update the choices for your filter in init method of your filter:

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

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

Note: I could not verify your query to get list of choices you want as i dont have the same DB. So That's up to you to have it correct.

这篇关于如何将当前登录的用户传递给filter.py,即在Django中基于请求的过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆