Let's say I have two models, Book and Page:
class Book(models.Model):
pass
class Page(models.Model):
book = models.ForeignKey(Book)
I need to delete a page and being redirected to the specific book that the page belonged to. To achieve this, I make a class based view to delete the page:
class PageDeleteView(DeleteView):
model = Page
def get_success_url(self, **kwargs):
return reverse_lazy('book_detail', self.book.pk)
The problem is that, since the object is deleted before get_success_url is called, this method fails, and I get a 404 error.
How could I do it?
Update:
Following the idea of @DrTyrsa, I have achieved it overriding the delete method, so the class would be as follows:
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)
Save object's pk
before deleting. In __init__
, for example. And name your URL patterns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With