python - Django 管理员 : sending signal on field change

标签 python django django-admin

当且仅当表单字段“状态”更新时,我需要触发信号。该信号工作正常,但无论向表单提交任何更改,都会触发该信号。

下面是我从 admin.py 重写的 OrderAdmin 类的 save_model:

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

最佳答案

您可以尝试重写 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

现在您可以在 save_model 中使用 if o.status != o._old_status

关于python - Django 管理员 : sending signal on field change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7356471/

相关文章:

python - 有没有办法在 Tkinter 中合并碰撞?

python - Django 评论

python - 在 Django Admin 中保存模型之前显示警告消息

python - 表 'MyDjango.django_admin_log' 不存在

python - 限制为 django admin 内联显示的条目的查询集

python - IntelliJ Python 3 检查 "Expected a dictionary, got a dict"是否是带有 **kwargs 的 super 的误报?

python按包含列表的长度对对象列表进行排序

python - 如何正确保存.npz格式的字典

django - 在 Django 中选择不同的单个列?

python - 该 View 未返回 HttpResponse 对象。它返回 None 而不是