Django如何从视图中删除对象?

时间:2012-10-09 09:26:55

标签: python django

我是Django的新手,我的DeleteView是这样编写的:

class ObjectDelete(DeleteView):
    def post(self, request, *args, **kwargs):
        blah blah
        return super(ObjectDelete, self).post(request, *args, **kwargs)

我对如何删除对象感到困惑,因为我在函数中的任何地方都没有看到object.delete

1 个答案:

答案 0 :(得分:4)

实际删除对象是由DeletionMixin完成的,DeletionMixindjango.views.generic.edit.BaseDeleteView使用的DeleteView的父级。

以下是{{3}}:

class DeletionMixin(object):
    """
    A mixin providing the ability to delete objects
    """
    success_url = None

    def delete(self, request, *args, **kwargs):
        """
        Calls the delete() method on the fetched object and then
        redirects to the success URL.
        """
        self.object = self.get_object()
        self.object.delete()
        return HttpResponseRedirect(self.get_success_url())

    # Add support for browsers which only accept GET and POST for now.
    def post(self, *args, **kwargs):
        return self.delete(*args, **kwargs)

    def get_success_url(self):
        if self.success_url:
            return self.success_url
        else:
            raise ImproperlyConfigured(
                "No URL to redirect to. Provide a success_url.")

使用get_object()获取要删除的对象。