猿问

ValueError:无法分配对象用户必须是“用户”实例

这对我来说很奇怪。我正在 Django 信号接收器内设置一个断点create_customer_settings来调试它。ValueError即使CustomerSettings成功创建了新对象,应用程序也会抛出。当我第二次尝试创建它时,我收到一个 UNIQUE 约束错误,但那是因为它已经成功添加。


为什么是ValueError什么时候isinstance(this_user, User) == True?


这是一个我可以安全地捕获并忽略的错误吗?是不是因为CustomerSettingsid与id 不同而有问题User?


create_customer_settings

@receiver(post_save, sender=User)

def create_customer_settings(sender, instance, created, **kwargs):

    if created:

      this_user = User.objects.get(id=instance.id)

      pdb.set_trace()

      CustomerSettings.objects.create(

          user=this_user, 

          email=this_user.email, 

          date_of_birth="1998-01-04", 

          in_private_mode=False

    )                                 

pdb.set_trace() 输出 1:

System check identified no issues (0 silenced).

October 29, 2018 - 23:42:57

Django version 2.1.1, using settings 'myapp.settings'

Starting development server at http://127.0.0.1:7000/

Quit the server with CONTROL-C.

> /src/myapp/myapp/models.py(36)create_customer_settings()

-> pdb.set_trace()

(Pdb) this_user

<User: new_user_8080>

(Pdb) isinstance(this_user, User)

True

(Pdb) CustomerSettings.objects.create(

    user=this_user, 

    email=this_user.email, 

    date_of_birth="1998-01-04", 

    in_private_mode=False

)                                 

*** ValueError: Cannot assign 

"<CustomerSettings: CustomerSettings object (6)>": 

"CustomerSettings.user" must be a "User" instance.


牧羊人nacy
浏览 571回答 2
2回答

慕田峪4524236

仔细检查您发布的代码是否是您正在运行的代码。该错误消息ValueError: Cannot assign "<CustomerSettings: CustomerSettings object (6)>": "CustomerSettings.user" must be a "User" instance意味着您正在尝试创建一个CustomerSettings实例,其中该user属性的实例CustomerSettingsid 为 6。我的猜测是您运行的内容与您发布的内容之间存在脱节。如果没有,那么有什么东西在调用create_customer_settings,instance参数是CustomerSettings.
随时随地看视频慕课网APP

相关分类

Python
我要回答