Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-admin: How to redirect to another URL after Object save? [duplicate]

In Django Admin, saving an Object always goes back to it's List of Objects. Now i want to go to the List of Invoice-Objects upon saving a Payment-Object.

I tried several things:

In admin.py:

@receiver(post_save, sender=Payment)
def custom_redirect(sender, instance, **kwargs):
    return HttpResponseRedirect('/admin/sales/invoice')

OR

class PaymentAdmin(VersionAdmin, admin.ModelAdmin):
    def change_view(self, request, object_id, extra_context=None):
        return HttpResponseRedirect('/admin/sales/invoice')

Instead of HttpResponseRedirect i tried using redirect() , but also with no effect. On inserting wrong code into post_save i get an error message - so it does get triggered, but the redirect does not happen.

Any hints would be very apreciated - as i'm stuck for days on this "simple" problem.

Thanks

like image 254
monkee Avatar asked Feb 14 '17 15:02

monkee


Video Answer


1 Answers

You can override the response_add and response_change methods.

from django.shortcuts import redirect

class PaymentAdmin(VersionAdmin, admin.ModelAdmin):
    def response_add(self, request, obj, post_url_continue=None):
        return redirect('/admin/sales/invoice')

    def response_change(self, request, obj):
        return redirect('/admin/sales/invoice')

It isn't possible to return a response from inside a signal handler. You don't want to override change_view because that handles saving the form as well as returning the response.

like image 106
Alasdair Avatar answered Nov 09 '22 22:11

Alasdair