2011-09-09 24 views
1

当且仅当表单字段“状态”更新时,我需要触发信号。信号正常工作,但无论提交表单有何变化,都会被触发。Django管理员:发送现场变化信号

下面是从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

建议:粘贴更多代码。从这段代码中无法分辨出任何内容。 –

+0

我添加了整个save_model覆盖以及我的模型。 –

回答

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_statussave_model

+0

在将“if o.status!= o._old_status”更改为“if obj.status!= obj._old_status”之后,这起作用。谢谢! –