基于 Django 类的 DeleteView 示例 [英] Example of Django Class-Based DeleteView

查看:20
本文介绍了基于 Django 类的 DeleteView 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道或可以请任何人制作 Django 基于类的通用 DeleteView 的简单示例?我想继承 DeleteView 并确保当前登录的用户在删除对象之前拥有该对象的所有权.任何帮助将不胜感激.提前致谢.

Does anyone know of or can anyone please produce a simple example of Django's class-based generic DeleteView? I want to subclass DeleteView and ensure that the currently logged-in user has ownership of the object before it's deleted. Any help would be very much appreciated. Thank you in advance.

推荐答案

这是一个简单的方案:

from django.views.generic import DeleteView
from django.http import Http404

class MyDeleteView(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

注意事项:

  • DeleteView 不会删除 GET 请求;这是您提供带有是的,我确定"按钮的确认模板(您可以在 template_name 类属性中提供名称)的机会,该按钮POSTs 到此查看
  • 与 404 相比,您可能更喜欢错误消息?在这种情况下,改写 delete 方法,在 get_object 调用后检查权限并返回自定义响应.
  • 不要忘记提供与(可选可自定义)success_url 类属性匹配的模板,以便用户可以确认对象已被删除.
  • The DeleteView won't delete on GET requests; this is your opportunity to provide a confirmation template (you can provide the name in the template_name class attribute) with a "Yes I'm sure" button which POSTs to this view
  • You may prefer an error message to a 404? In this case, override the delete method instead, check permissions after the get_object call and return a customised response.
  • Don't forget to provide a template which matches the (optionally customisable) success_url class attribute so that the user can confirm that the object has been deleted.

这篇关于基于 Django 类的 DeleteView 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆