django-admin:保存对象后如何重定向到另一个 URL? [英] django-admin: How to redirect to another URL after Object save?
问题描述
在 Django Admin 中,保存对象总是返回到它的对象列表.现在我想在保存付款对象后转到发票对象列表.
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.
我尝试了几件事:
在 admin.py 中:
In admin.py:
@receiver(post_save, sender=Payment)
def custom_redirect(sender, instance, **kwargs):
return HttpResponseRedirect('/admin/sales/invoice')
或
class PaymentAdmin(VersionAdmin, admin.ModelAdmin):
def change_view(self, request, object_id, extra_context=None):
return HttpResponseRedirect('/admin/sales/invoice')
我尝试使用 redirect() 而不是 HttpResponseRedirect ,但也没有效果.在将错误代码插入 post_save 时,我收到一条错误消息 - 所以它会被触发,但不会发生重定向.
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.
谢谢
推荐答案
你可以覆盖 response_add
和 response_change
方法.
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')
不可能从信号处理程序内部返回响应.您不想覆盖 change_view
,因为它会处理保存表单以及返回响应.
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.
这篇关于django-admin:保存对象后如何重定向到另一个 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!