开发者

Django admin: sending signal on field change

I need to trigger a signal if and only if form field "status" is updated. The signal works fine, but is being triggered regardless of any change submissions to the form.

Below is my save_model override from admin.py, for the OrderAdmin class:

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()  

Here is my model:

class Order(DirtyFieldsMixin, models.Model):

StatusOptions = (
  ('Pending Confirmation', 'Pending Confir开发者_运维知识库mation'),
  ('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)')


You can try overriding ModelAdmin.get_object to add a flag to your instance:

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

Now you can use if o.status != o._old_status in save_model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜