我有一个具有confidential
字段(布尔)的detailView /模板,我希望详细信息页面只能由员工(或更高)访问。我目前通过在模板中添加以下内容使其成功:
{% if enzymes.confidential == True %}
{% if user.is_staff %}
# confidential data is listed here
{% else %}
<p>You do not have access to this page</p>
{% endif %}
{% else %}
# non confidential data is listed here
{% endif %}
但是,我想知道我是否不能在我的视图中应用过滤器?我使用的视图如下所示(包括我尝试的一些剩余部分)。
class DetailView(generic.DetailView):
template_name = 'gts/detail.html'
model = Enzymes
# The active get_context_data
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
enzyme = context['object']
activities = Activitydiagram.objects.filter(enzymes=enzyme)
spectras = Spectraimage.objects.filter(enzymes=enzyme)
enzymeactivities = Enzymeactivity.objects.filter(enzymes=enzyme)
context['activities'] = activities
context['spectras'] = spectras
context['enzymeactivities'] = enzymeactivities
return context
# This was my WIP attempt
"""def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
if self.request.user.is_staff:
enzyme = context['object']
activities = Activitydiagram.objects.filter(enzymes=enzyme)
spectras = Spectraimage.objects.filter(enzymes=enzyme)
enzymeactivities = Enzymeactivity.objects.filter(enzymes=enzyme)
context['activities'] = activities
context['spectras'] = spectras
context['enzymeactivities'] = enzymeactivities
else:
# TODO: Load only confidential=False enzymes here
enzyme = context['object']
activities = Activitydiagram.objects.filter(enzymes=enzyme)
spectras = Spectraimage.objects.filter(enzymes=enzyme)
enzymeactivities = Enzymeactivity.objects.filter(enzymes=enzyme)
context['activities'] = activities
context['spectras'] = spectras
context['enzymeactivities'] = enzymeactivities
return context"""
答案 0 :(得分:1)
一种典型的方法是覆盖get_queryset
方法,如果用户不是工作人员,则过滤查询集。如果非工作人员试图访问机密项目,他们将获得404页面。
class DetailView(generic.DetailView):
template_name = 'gts/detail.html'
model = Enzymes
def get_queryset(self):
queryset = super(DetailView, self).get_queryset()
if not request.user.is_staff:
queryset = queryset.filter(confidential=False)
return queryset