假设我有两个模型,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的想法,我已经实现了覆盖delete方法,所以类如下:
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)