假设我有两个模型,Book 和 Page:
class Book(models.Model):
pass
class Page(models.Model):
book = models.ForeignKey(Book)
我需要删除一个页面并被重定向到该页面所属的特定书籍。为此,我创建了一个基于类的视图来删除页面:
class PageDeleteView(DeleteView):
model = Page
def get_success_url(self, **kwargs):
return reverse_lazy('book_detail', self.book.pk)
问题是,由于在调用 get_success_url 之前删除了对象,因此此方法失败,并且出现 404 错误。
我怎么能做到?
更新:
遵循@DrTyrsa 的想法,我已经实现了它覆盖删除方法,所以类如下:
reverse_lazy = lambda name=None, *args : lazy(reverse, str)(name, args=args)
class PageDeleteView(DeleteView):
model = Page
def get_success_url(self, **kwargs):
return reverse_lazy('book_detail', self.book.pk)
def delete(self, request, *args, **kwargs):
self.book_pk = self.get_object().book.pk
return super(PageDeleteView, self).delete(request, *args, **kwargs)