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')
OR
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屋!