2011-09-09 44 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」之後,這起作用。謝謝! –