如果我是你,我会在模板中这样做:
{% if user == post.author %}
display edit button
{% else %}
display view button or something else
{% endif %}
另一种变体(如果您想在视图中执行所有逻辑)是创建一个 mixin:
class CanEditMixin(object):
def get_context_data(self, **kwargs):
"""
The method populates Context with can_edit var
"""
# Call the base implementation first to get a context
context = super(CanEditMixin, self).get_context_data(**kwargs)
#Update Context with the can_edit
#Your logic goes here (something like that)
if self.request.user == self.get_object().author
context['can_edit']=True
else:
context['can_edit']=False
return context
然后你需要更新你的视图(顺序很重要):
class PostDetailView(CanEditMixin, LoginRequiredMixin, DetailView):
#your view
和你的模板:
{% if can_edit %}
display edit button
{% else %}
display view button or something else
{% endif %}
此外,根据您的问题的具体情况,您可能对django object-level permission packages感兴趣。这些包允许您为用户添加编辑给定对象的权限。在这种情况下,您可以在模板中写下类似的内容:
{% if perms.post.can_edit %}
display edit button
{% else %}
display view button or something else
{% endif %}
django 文档的链接。