【问题标题】:Django - Permissions and DeleteView, is this a good way to do it?Django - 权限和 DeleteView,这是一个好方法吗?
【发布时间】:2025-11-23 11:00:02
【问题描述】:

嗨,我有一个工作视图。我想知道这是最好的还是好的方法。我想要一个删除照片对象的删除视图,但前提是登录的用户是与该对象关联的。

这是我的意见.py

class PhotoDelete(DeleteView):
    model = Photo
    template_name = 'otologue/photo_delete.html'
    success_url = reverse_lazy('otologue:photos')

    def get(self, request, *args, **kwargs):
        object_instance = self.get_object()  # Get the object
        object_user = object_instance.photoextended.user  # Get the user who owns the object

        user = get_object_or_404(User, username=self.request.user)  # Get the user in the view
        if object_user != user:  # See if the object_user is the same as the user
            return HttpResponseForbidden('Permission Error')
        else:
            return render(request, self.template_name, {'object': object_instance})

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

如果您需要更多信息,例如型号等,请索取。

【问题讨论】:

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


    【解决方案1】:
    • 你不必调用get_object_or_404(),因为self.request.user已经包含了一个User实例,所以你可以直接比较。

    • 您应该调用(并返回结果)DeleteView 的get() 方法,而不是自己渲染模板。

    • 我也会使用 LoginRequiredMixin 代替装饰器,因为您的 dispatch() 现在除了调用 super 的方法之外什么都不做。

    • 请注意,实际删除是在post() 方法中完成的。您应该将您的用户检查移至dispatch() 方法,否则可能会使用伪造的 POST 请求绕过检查。

    要更好地了解 DeleteView 在其方法中的作用,请查看它的源代码(例如 ccbv.co.uk

    【讨论】:

    • 对于DeleteView,我在使用LoginRequiredMixin 时遇到问题。虽然在其他视图中它正在工作,但如果 od DeleteView 它运行 dispatch 无论如何(在 POST 和 GET 中)。
    最近更新 更多