Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using get_success_url on a DeleteView when relevant data has been removed

In a Django application working with recipes I have subclassed DeleteView to create my IngredientListItemDeleteView, but I would like the result of get_success_url to depend on a property of the item that was just deleted.

I would like to do something like this:

def get_success_url(self):
    item = get_object_or_404(IngredientListItem, pk=self.kwargs['pk'])   # -> 404
    return this_item.recipe.get_absolute_url()

I understand that I get a 404 error because the item in question no longer exists but I have had no luck storing the relevant information about the item (namely, its containing recipe) before it gets deleted. For instance, if I put into the get method any code like

self.success_url = get_object_or_404(IngredientListItem, 
                                pk=self.kwargs['pk']).recipe.get_absolute_url()

then by the time success_url is looked at (after deletion), it has the value None.

How can I make my success URL depend on this property of the deleted item?

like image 249
bryn Avatar asked Jul 29 '13 10:07

bryn


1 Answers

In Django 1.6, the delete method has been changed so that the get_success_url method is called before the object is deleted.

def delete(self, request, *args, **kwargs):
    """
    Calls the delete() method on the fetched object and then
    redirects to the success URL.
    """
    self.object = self.get_object()
    success_url = self.get_success_url()
    self.object.delete()
    return HttpResponseRedirect(success_url)

I recommend you override your delete method as above, until you upgrade to Django 1.6. If you need to do this for multiple classes, you could create a mixin.

Note that you don't need to fetch the item from the database with get_item_or_404 -- you can access it in your get_success_url method as self.object.

like image 156
Alasdair Avatar answered Nov 16 '22 15:11

Alasdair