Redirect to the parent after deleting the object using the general view DeleteObject

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 the page and redirect it to the specific book to which the page belonged. To do this, I create 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 calling get_success_url, this method fails, and I get 404 error.

How can i do this?

Update:

Following @DrTyrsa's idea, I achieved this by overriding the delete method, so the class will look like this:

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)
+5
source share
1 answer

pk . , __init__. URL.

+5

All Articles