有谁知道或者可以请任何人制作一个简单的 Django 基于类的通用 DeleteView 示例吗?我想继承 DeleteView 并确保当前登录的用户在删除对象之前拥有该对象的所有权。任何帮助将不胜感激。先感谢您。
问问题
53397 次
4 回答
63
这是一个简单的:
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
类属性中提供名称)的机会,该模板带有“是的,我确定”按钮,该按钮位于POST
此视图- 您可能更喜欢错误消息而不是 404?在这种情况下,请改写该
delete
方法,在get_object
调用后检查权限并返回自定义响应。 - 不要忘记提供与(可选自定义)
success_url
类属性匹配的模板,以便用户可以确认对象已被删除。
于 2011-04-03T20:54:19.527 回答
44
我基本上已经对一些基于类的通用视图进行了细分,以做到这一点。主要区别是我只是过滤掉了查询集。我不能保证这种方法是好是坏,但它对我来说更有意义。
随意忽略“MessageMixin”——它只是为了使用 Django 消息框架(带有为每个视图指定的变量)轻松呈现消息。这是我为我们的网站编写的代码:
意见
from django.views.generic import CreateView, UpdateView, \
DeleteView, ListView, DetailView
from myproject.core.views import MessageMixin
class RequestCreateView(MessageMixin, CreateView):
"""
Sub-class of the CreateView to automatically pass the Request to the Form.
"""
success_message = "Created Successfully"
def get_form_kwargs(self):
""" Add the Request object to the Form's Keyword Arguments. """
kwargs = super(RequestCreateView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
class RequestUpdateView(MessageMixin, UpdateView):
"""
Sub-class the UpdateView to pass the request to the form and limit the
queryset to the requesting user.
"""
success_message = "Updated Successfully"
def get_form_kwargs(self):
""" Add the Request object to the form's keyword arguments. """
kwargs = super(RequestUpdateView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
def get_queryset(self):
""" Limit a User to only modifying their own data. """
qs = super(RequestUpdateView, self).get_queryset()
return qs.filter(owner=self.request.user)
class RequestDeleteView(MessageMixin, DeleteView):
"""
Sub-class the DeleteView to restrict a User from deleting other
user's data.
"""
success_message = "Deleted Successfully"
def get_queryset(self):
qs = super(RequestDeleteView, self).get_queryset()
return qs.filter(owner=self.request.user)
用法
然后,您可以轻松创建自己的视图来使用此类功能。例如,我只是在我的 urls.py 中创建它们:
from myproject.utils.views import RequestDeleteView
#...
url(r'^delete-photo/(?P<pk>[\w]+)/$', RequestDeleteView.as_view(
model=Photo,
success_url='/site/media/photos',
template_name='site/media-photos-delete.html',
success_message='Your Photo has been deleted successfully.'
), name='fireflie-delete-photo-form'),
形式
需要注意的重要一点:我已经重载了那些 get_form_kwargs() 方法来为我的表单提供一个“请求”实例。如果您不希望将 Request 对象传递给 Form,只需删除那些重载的方法。如果您想使用它们,请按照以下示例进行操作:
from django.forms import ModelForm
class RequestModelForm(ModelForm):
"""
Sub-class the ModelForm to provide an instance of 'request'.
It also saves the object with the appropriate user.
"""
def __init__(self, request, *args, **kwargs):
""" Override init to grab the request object. """
self.request = request
super(RequestModelForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
m = super(RequestModelForm, self).save(commit=False)
m.owner = self.request.user
if commit:
m.save()
return m
这比你问的要多一些——但它有助于了解如何对 Create 和 Update 视图执行相同的操作。同样的通用方法也可以应用于 ListView 和 DetailView。
消息混音
以防万一有人想要我使用的 MessageMixin。
class MessageMixin(object):
"""
Make it easy to display notification messages when using Class Based Views.
"""
def delete(self, request, *args, **kwargs):
messages.success(self.request, self.success_message)
return super(MessageMixin, self).delete(request, *args, **kwargs)
def form_valid(self, form):
messages.success(self.request, self.success_message)
return super(MessageMixin, self).form_valid(form)
于 2012-06-05T19:50:34.163 回答
7
最简单的方法是预过滤查询集:
from django.views.generic import DeleteView
class PostDeleteView(DeleteView):
model = Post
success_url = reverse_lazy('blog:list_post')
def get_queryset(self):
owner = self.request.user
return self.model.objects.filter(owner=owner)
于 2017-09-11T16:22:37.740 回答
1
我建议最好(也是最简单)的方法是使用UserPassesTestMixin
它,它可以让您更清晰地分离关注点。
例子:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import DeleteView
class MyDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
def test_func(self):
""" Only let the user access this page if they own the object being deleted"""
return self.get_object().owner == self.request.user
于 2017-05-25T12:07:31.470 回答