当且仅当表单字段“status”更新时,我才需要触发信号。信号工作正常,但无论表单是否有任何变更提交,都会被触发。
以下是来自admin.py的save_model覆盖,适用于OrderAdmin类:
def save_model(self, request, obj, form, change):
if not change:
if not request.user.is_superuser:
obj.organization = request.user
if Order().is_dirty():
custom_signals.notify_status.send(sender=self, status=obj.status)
obj.save()
这是我的模特:
class Order(DirtyFieldsMixin, models.Model):
StatusOptions = (
('Pending Confirmation', 'Pending Confirmation'),
('Confirmed', 'Confirmed'),
('Modified', 'Modified'),
('Placed', 'Placed'),
('En Route', 'En Route'),
('Completed', 'Completed'),
('Cancelled', 'Cancelled'),
)
organization = models.ForeignKey(User, related_name='orders', default=1, help_text='Only visible to admins.')
status = models.CharField(max_length=50, choices=StatusOptions, default=1, help_text='Only visible to admins.')
order_name = models.CharField(max_length=22, blank=True, help_text='Optional. Name this order for easy reference (example: Munchies)')
contact_person = models.ForeignKey(Contact, help_text='This person is in charge of the order. We may contact him/her regarding this order.')
delivery_date = models.DateField('delivery day', help_text='Please use YYYY-MM-DD format (example: 2011-11-25)')
答案 0 :(得分:2)
您可以尝试覆盖ModelAdmin.get_object
以向您的实例添加标记:
def get_object(self, request, object_id):
o = super(Order, self).get_object(request, object_id)
if o:
o._old_status = o.status
return o
现在,您可以在if o.status != o._old_status
中使用save_model
。