Django Admin变更列表提交重定向



在变更列表视图中直接提交变更后,是否可以让django重定向到另一个页面?(指定list_editable字段后(

已经尝试了不同的方法response_post_save_changeresponse_changeresponse_add,但都不起作用。

我怀疑它可能在changelist_view中,不知道如何处理它,因为它处理表单保存。

您是正确的,您需要覆盖管理类中的changelist_view方法。该方法返回一个类似响应的对象,并且肯定可以自定义该值。

方法#1:将整个ModelAdmin.changelist_view方法复制到您自己的管理类中,然后对其进行修改以满足您的需求。对于您的情况来说,这可能是最安全的选择,即使您在此方法中只更改一行代码(此时为99行长(。

class MyAdmin(admin.ModelAdmin):
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
"""
The 'change list' admin view for this model.
"""
... omitting code that leads up to line 1756 (v3.2)  ...
# Handle POSTed bulk-edit data.
if request.method == 'POST' and cl.list_editable and '_save' in request.POST:
... omitting more code ...
# This is it. Line 1785: change this to meet your needs
return HttpResponseRedirect(request.get_full_path())
... omitting the rest of the code after this line ...

方法#2:通过super()调用它,然后检查/更改结果。这个可能可能不可靠(代码中的注释(,但它看起来是这样的:

class MyAdmin(admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
request_full_path = request.get_full_path()
response = super().changelist_view(request, extra_context)
# This is not a foolproof condition! In the changelist_view method, you can
# see that it returns this redirect in the following scenarios:
# - if action_failed (line ~1745 in django.contrib.admin.options, v3.2)
# - successful bulk update of the changelist (this is the use case you're targeting)
if isinstance(response, HttpResponseRedirect) and response.location == request_full_path:
# do something here, like return a redirect to a different URL
return HttpResponseRedirect(reverse('my_url_name'))
return response

因此,我不确定您将如何确定这两个条件中的哪一个导致它返回具有完全相同参数(相同的status_code和相同的location(的HttpResponseRedirect对象-一个是提交失败,另一个是成功提交!但是你可能在你的应用程序中有一些这样做的方式,所以我就到此为止。

我会自己选择方法#1,尽管我肯定不喜欢必须复制到你自己的代码库中的代码量,也不喜欢将来必须维护它/考虑它。但这可能是最好的方式。

最新更新