Reputation: 53
As of Django 1.7 it is possible to override an Admin Model's response_delete
method to force it to redirect to a custom URL after deletion.
class MyAdmin(admin.ModelAdmin):
def response_delete(self, request, obj_display, obj_id):
return HttpResponseRedirect("my_url")
I need to take this a step further and redirect to the parent of the deleted object, which seems like it should be a fairly common use case.
However due to deletion of the object there is no obj
available to get the parent ID from.
The hacky solution I found was to pass the parent ID in the Unicode representation of the child object (obj_display
), then parse the string to find it:
obj_display = '1 (Product 123)'
integers = re.findall(r'\d+', obj_display)
product_id = int(integers[1])
product_id = 123
However, this seems like an inelegant solution. For example, if the unicode method of the object changed the redirect could break. Is there a better way?
Edit
by 'parent' and 'child' I mean the deleted ('child') object had a foreign key to another object (its 'parent')
Upvotes: 1
Views: 1711
Reputation: 655
If you want to retain the ability to use rest of delete_view
, I recommend overwriting both delete_view
and response_delete
like this:
class MyModelAdmin(admin.ModelAdmin):
deleted_fk = None
def delete_view(self, request, object_id, extra_context=None):
self.deleted_fk = MyModel.objects.get(id=object_id).fk
return super(MyModelAdmin, self).delete_view(request, object_id, extra_context)
def response_delete(self, request, obj_display, obj_id):
return redirect('url to deleted_fk')
Upvotes: 1
Reputation: 6933
You can overwrite this method delete_view (there you can get the parent of the object, before delete it) and instead of doing this return self.response_delete(request, obj_display, obj_id)
, just do the redirect to the parent admin page.
Upvotes: 0