Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect on admin Save

How can I redirect a user to different app on Save?

I have two app, say app1 and app2. If a user clicks on Save in app2 then it should be redirected to app1 rather then the default page.

I don't want to do a customform.

like image 236
ha22109 Avatar asked Aug 27 '09 09:08

ha22109


2 Answers

To change the redirect destination after save in the admin, you need to override response_add() (for adding new instances) and response_change() (for changing existing ones) in the ModelAdmin class.

See the original code in django.contrib.admin.options.

Quick examples to make it clearer how to do this (would be within a ModelAdmin class):

from django.core.urlresolvers import reverse

def response_add(self, request, obj, post_url_continue=None):
    """
    This makes the response after adding go to another 
    app's changelist for some model
    """
    return HttpResponseRedirect(
        reverse("admin:otherappname_modelname_changelist")
    )


def response_change(self, request, obj, post_url_continue=None):
    """
    This makes the response go to the newly created
    model's change page without using reverse
    """
    return HttpResponseRedirect("../%s" % obj.id)
like image 159
Daniel Roseman Avatar answered Oct 22 '22 04:10

Daniel Roseman


To add to @DanielRoseman's answer, and you DON'T want the user redirected when they choose Save and continue and not the Save button, then you could use this solution instead.

def response_add(self, request, obj, post_url_continue="../%s/"):
    if '_continue' not in request.POST:
        return HttpResponseRedirect(get_other_app_url())
    else:
        return super(MyModelAdmin, self).response_add(request, obj, post_url_continue)

def response_change(self, request, obj):
    if '_continue' not in request.POST:
        return HttpResponseRedirect(get_other_app_url())
    else:
        return super(MyAdmin, self).response_change(request, obj)
like image 42
Dan Mantyla Avatar answered Oct 22 '22 04:10

Dan Mantyla