使用基于 Class 的视图,将对模板的一部分的访问限制为属于组的一部分的用户。姜戈 2.0
Restrict access to a part of a template to users that is part of a group using Class based views. Django 2.0
我想限制某些组中的用户访问 HTML 模板的部分内容。我有一个基于 class 的视图,如下所示:
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'
使用基于 class 的视图时,将上下文变量添加到模板中的方法是覆盖 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。
我想限制某些组中的用户访问 HTML 模板的部分内容。我有一个基于 class 的视图,如下所示:
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'
使用基于 class 的视图时,将上下文变量添加到模板中的方法是覆盖 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。