因此,最好的做法是不使用
Django Signals
完全尤其是当存在内置方法时,例如
ModelAdmin.response_add
,并从模型中离开
admin.py
:
# ./app/utils.py
def send_mail_to_admin(obj):
hotels = obj.hotels.all().order_by('cost')
message = 'Tour ID ' + obj.pk + '\n'
message += 'Country: ' + obj.country_name + ' City: ' + obj.city_name + '\n'
message += 'Hotels: \n'
for hotel in hotels:
message += hotel.name + ' ' + hotel.star + ' ' + hotel.cost + '\n'
send_mail(
'From Admin',
message,
'no-reply@example.com',
['admin@example.com'],
fail_silently=False,
)
# ./app/admin.py
from .utils import send_mail_to_admin
class ToursAdmin(admin.ModelAdmin):
exclude = ('created_at',)
list_display = ('country_name',)
ordering = ('created_at',)
inlines = (HotelsInline,)
def response_add(self, request, obj, post_url_continue=None):
send_mail_to_admin(obj)
return super().response_add(request, obj, post_url_continue)