本文介绍了基于Django类的DeleteView示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有人知道或可以任何人制作一个简单的Django类的通用DeleteView示例?我想对DeleteView进行子类化,并确保当前登录的用户在删除对象之前拥有该对象的所有权。任何帮助将非常感谢。谢谢你提前。解决方案
这是一个简单的例子:
<$ p来自django.views.generic导入的$ p>
从django.http导入DeleteView
导入Http404
class MyDeleteView(DeleteView):
def get_object(self, queryset = None)
Hook保证对象由request.user拥有。
obj = super(MyDeleteView,self).get_object()
如果不是obj。所有者== self.request.user:
raise Http404
return obj
注意事项:
-
DeleteView
不会在GET
请求;这是您提供确认模板的机会(您可以在template_name
类属性中提供名称),其中包含是我确定按钮,其中POST
到此视图 - 您可能希望向404发送错误消息?在这种情况下,请重写
delete
方法,在get_object
调用后检查权限,并返回自定义响应。 li>
- 不要忘记提供与(可选择定制的)
success_url
类属性匹配的模板,以便用户可以确认对象具有已被删除。
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.
解决方案
Here's a simple one:
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
Caveats:
- The
DeleteView
won't delete onGET
requests; this is your opportunity to provide a confirmation template (you can provide the name in thetemplate_name
class attribute) with a "Yes I'm sure" button whichPOST
s to this view - You may prefer an error message to a 404? In this case, override the
delete
method instead, check permissions after theget_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示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!