【问题标题】:Restrict access to a part of a template to users that is part of a group using Class based views. Django 2.0使用基于类的视图限制属于组的用户访问模板的一部分。姜戈 2.0
【发布时间】:2018-11-09 21:21:00
【问题描述】:

我想限制某些组中的用户访问 HTML 模板的某些部分。我有一个基于类的视图,如下所示:

Views.py

class PostListView(ListView):
    model = BlogPost
    paginate_by = 10
    template_name = 'main/mysite.html'

使用基于函数的视图,我可以使用来自In Django, how do I check if a user is in a certain group?request.user.groups.filter(name='GROUP_NAME').exists() 限制对基于某人组的模板的访问

我尝试像这样更改我的 view.py 和 HTML 模板:

views.py

class PostListView(ListView):
    model = BlogPost
    paginate_by = 10
    template_name = 'main/mysite.html'

    def dispatch(self, request):
        in_group =  request.user.groups.filter(name='GROUP_NAME').exists()
        return in_group

HTML 模板

....
{% if in_group %}
some code here shows up if user belong to group
{% endif %}
....

当用户不是该组的成员时,这将给我正确的显示,但是当他们是正确组的成员时,我得到一个归属错误:

Exception Type: AttributeError at /mysite
Exception Value: 'bool' object has no attribute 'get'

【问题讨论】:

    标签: django django-class-based-views django-permissions


    【解决方案1】:

    在使用基于类的视图时,将上下文变量放入模板的方法是覆盖 get_context_data() 方法:

    class PostListView(ListView):
        model = BlogPost
        paginate_by = 10
        template_name = 'main/mysite.html'
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['in_group'] =  self.request.user.groups.filter(name='GROUP_NAME').exists()
            return context
    

    有关get_context_data() 的更多信息,请参阅Django docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-16
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 2011-10-31
      • 2012-11-19
      相关资源
      最近更新 更多