重定向管理员保存

ha2*_*109 25 django django-admin

如何在保存时将用户重定向到其他应用?

我有两个应用程序,说app1app2.如果用户单击"保存",app2则应将其重定向到app1默认页面.

我不想做自定义表单.

Dan*_*man 93

要在admin中保存后更改重定向目标,您需要覆盖response_add()(用于添加新实例)和response_change()(用于更改现有实例)ModelAdmin.

请参阅原始代码django.contrib.admin.options.

如果您希望人们继续在StackOverflow上帮助您,您需要接受问题的答案.

快速示例,使其更清楚如何执行此操作(将在ModelAdmin类中):

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 apps 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])
Run Code Online (Sandbox Code Playgroud)

  • 输入错误与它有什么关系?您已经在StackOverflow上询问了35个问题,并且您没有接受单个问题的最佳答案.这是非常糟糕的举止. (9认同)
  • 这是你应该接受的更好的答案 (3认同)

Dan*_*yla 35

要添加到@ DanielRoseman的答案,并且您不希望用户在选择" 保存并继续"而不是"保存"按钮时重定向,则可以使用此解决方案.

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)
Run Code Online (Sandbox Code Playgroud)


ha2*_*109 -9

def change_view(自身、请求、object_id、extra_context=None):

result = super(mymodeladmin, self).change_view(request, object_id, extra_context)

result['Location'] = "your location"

return result
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个很好的答案:如果change_view不成功会发生什么?另外,分配给 result['Location'] 不太像 django (即使它可能有效)。上面的答案(丹尼尔·罗斯曼)是一个很好的答案。 (5认同)