我有一个User
模型,它在一个名为 core 的应用程序中扩展了AbstractUser
模型。我在 * 设置中将此模型用作AUTH_USER_MODEL
。py*.我还有一个UserProfile
模型,它与User
有一对一的关系。我的目标是,每当同时创建一个新用户时,都要创建一个UserProfile。
# file name: core/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
email = models.EmailField(unique=True)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
**问题:**当我使用shell创建一个新用户时,我得到这个错误:
>>> bob = User.objects.create_user(email="bob@outlook.com", username="bob")
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'ModelBase'
The above exception was the direct cause of the following exception:
TypeError: Field 'id' expected a number but got <class 'core.models.User'>.
During handling of the above exception, another exception occurred:
ValueError: Cannot assign "<class 'core.models.User'>": "UserProfile.user" must be a "User" instance.
>>>
我应该如何解决这个错误?
为了在每次创建新的User
时创建UserProfile
,我使用如下所示的信号:
# file name: core/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from core.models import User, UserProfile
@receiver(post_save, sender=User)
def create_userprofile(sender, **kwargs):
try:
UserProfile.objects.get(user=sender)
except Exception:
sender.userprofile = UserProfile.objects.create(user=sender)
我已经在app config类中注册了这个信号:
# file name: core/apps.py
from django.apps import AppConfig
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'core'
def ready(self):
from . import signals
return super().ready()
1条答案
按热度按时间uyto3xhc1#
使用上面的方法可能不会以您预期的方式工作,因为您没有添加:
create_user_profile
函数中缺少instance
和created
。signals.py
文件应该是: