【问题标题】:How to put condition in django signals如何在 django 信号中放置条件
【发布时间】:2020-06-04 12:54:24
【问题描述】:

我在医院管理系统上工作。在这个用户中,我首先注册为医生或患者,我有 userprofileinfo 模型。我也有用户注册的配置文件模型,这里出现问题我想要配置文件是仅在用户类型为 pateint 时创建,但我不知道如何在 django Signals 中检查条件。我尝试了一些方法,但它显示以下错误

type object 'UserProfileInfo' has no attribute 'instance'

文件:- userprofileinfo.py patientprofile.py

编辑:- 在一个很好的建议中,我做出了更改,例如当用户注册为 Doctor is_staff 时设置为 true,但当注册为患者时 is_staff 为 false,但当我在信号中使用它时,它总是返回 false。指向注意到在 django 管理站点中 is_staff 被勾选为医生和超级

@receiver(post_save, sender=User)
def update_profile_signal(sender, instance, created, **kwargs):


        if created:
            if instance.is_staff:
                PateintProfile.objects.create(user=instance)
                instance.pateintprofile.save()

【问题讨论】:

  • 请上传您的代码。不是图!!!使用适当的缩进上传您的问题

标签: django django-models


【解决方案1】:

尝试在信号中做 您应该使用创建的实例

检查条件
@receiver(post_save, sender=User)
def update_profile_signal(sender, instance, created, **kwargs):
    if created:
        if instance.user_type=="2": # Check here
             PateintProfile.objects.create(user=instance)
             instance.pateintprofile.save()

试试这些东西然后告诉我

【讨论】:

  • No Success 它显示错误:- 'User' 对象没有属性 'user_type'
  • 'User' 对象没有属性 'user_type'
  • 我也试过这个 [instance.userprofileinfo.user_type == "2"] 或 [user.userprofileinfo.user_type == "2" ]
  • 在这种情况下,您在创建之前确实访问了用户配置文件,您应该检查医生的 is_staff 属性和患者的正常属性,因此在创建用户后,您检查 instance.is_staff 被称为医生,否则您需要检查用户已创建
  • 在创建用户配置文件之前,您永远不会访问它并通过错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 2012-08-08
  • 2015-10-08
  • 1970-01-01
  • 2020-04-13
  • 2020-08-18
  • 2011-05-14
相关资源
最近更新 更多