Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to parent after deleting an object with DeleteObject generic view

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)
like image 482
jantoniomartin Avatar asked May 17 '12 07:05

jantoniomartin


1 Answers

Save object's pk before deleting. In __init__, for example. And name your URL patterns.

like image 192
DrTyrsa Avatar answered Nov 14 '22 19:11

DrTyrsa