使用Django的CBV,我该如何检查request.user == my_model.user?

时间:2012-09-12 19:40:43

标签: django

当我使用基于功能的视图时,我经常这样做:

def my_view(request, username):
  user = get_object_or_404(User, username = username)
  if user != request.user:
    return HttpRequestForbidden()

此代码确保只有用户john才能访问/users/john/edit/等网页。

如何使用基于类的视图执行相同的操作?

1 个答案:

答案 0 :(得分:2)

我的问题似乎与Example of Django Class-Based DeleteView

重复

这是怎么做的:

def get_object(self, queryset=None):
    """ Hook to ensure object is owned by request.user. """
    obj = super(MyDeleteView, self).get_object()
    if not obj.owner == self.request.user:
        raise Http404
    return obj