简体   繁体   English

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

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

I want to restrict the views for each user ie 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. 为此,我创建了一个过滤器,我想在其中传递“登录用户”详细信息。

Below is the snapshot of filter.py 以下是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']

And i am using this filter in my views.py 我在我的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})

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. 现在的问题是,当我在上面的示例中以uername1的形式传递用户的硬编码值(如用户名)时,它工作正常,但是有100个用户,所以我想直接从请求传递值。

Means when i am passing request.user in place of username it is not working. 表示当我通过request.user代替用户名时,它不起作用。

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)

Problem is in filter.py i am not able to get request.user 问题在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

Have you checked the constructor of FilterSet? 您是否检查过FilterSet的构造函数? It looks like this: 看起来像这样:

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

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. 因此,我相信,如果正确实例化了过滤器,则可以访问过滤器中的当前请求,并且应该能够访问request.user。

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

update 更新

AFter you change the thing i mentioned. 之后,您更改我提到的内容。 you can update the choices for your filter in init method of your filter: 您可以在过滤器的init方法中更新过滤器的选择:

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. 因此,这取决于您自己是否正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Django 中,如何查询登录用户的 MYSQL 数据库? (即没有硬编码用户 ID 的特定用户的结果) - In Django, how do I query a MYSQL database for the logged in user? (i.e results for specific user without hardcoding the user id) 如何过滤当前登录用户的 Django 表单下拉列表(基于类的视图) - How to filter Django Form dropdown for currently logged-in user (Class Based Views) Django当我使用基于类的视图时,如何在表单中传递request.user(当前登录的用户)? - Django How I can pass request.user(current logged user) in forms when I use class based view? 根据当前登录的用户自定义django表单 - Customizing django form based on currently logged in user 在models.py文件中获取当前登录的Django用户? - Get the currently logged in Django user in a models.py file? 如何将当前登录的用户默认传递给表单 - How to pass the currently logged in user as default to a form 如何向当前登录的用户 Django 发送电子邮件 - How to send an email to currently logged in user Django Django:如何测试用户当前是否已登录 - Django: How to test if a user is currently logged in 我无法在 django 中进行查询以过滤掉当前登录用户正在关注的那些用户的帖子 - I can't make query in django to filter out posts from those users that the currently logged in user is following Django:过滤当前登录用户的 ListView(多多多场) - Django: Filter ListView on currently logged-in user (manytomanyfield)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM