gpt4 book ai didi

python - Django models.py OneToOneField --- 帮助创建两个模型之间的关系

转载 作者:太空宇宙 更新时间:2023-11-03 21:31:29 25 4
gpt4 key购买 nike

我在测试位于不同应用中的两个模型(CustomUser 和 Profile)之间的关系时遇到问题。我希望有人能找出我哪里出错了:

这是我的 profile/models.py --- 您可以看到我的用户字段尝试与我的 users/models.py 创建 OneToOne:

from django.db import models

from core.models import TimeStampedModel

class Profile(TimeStampedModel):
user = models.OneToOneField('users.CustomUser', on_delete=models.CASCADE)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
bio = models.TextField(blank=True)
image = models.URLField(blank=True)

def __str__(self):
return self.user.username

这是我的 users/models.py:

class CustomUser(AbstractBaseUser, PermissionsMixin, TimeStampedModel):
username = models.CharField(db_index=True, max_length=255, unique=True)
email = models.EmailField(db_index=True, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_provider = models.BooleanField(default=False)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

objects = CustomUserManager()

def __str__(self):
return self.email

@property
def token(self):
return self._generate_jwt_token()

def get_short_name(self):
return self.username

def _generate_jwt_token(self):
dt = datetime.now() + timedelta(days=60)

token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')

return token.decode('utf-8')

所以我们的想法是,当我创建新用户时,也会自动创建一个配置文件。为此,我在用户应用程序中使用 post_save 信号:

用户/signals.py:

from django.db.models.signals import post_save
from django.dispatch import receiver

from conduit.apps.profiles.models import Profile

from .models import User

@receiver(post_save, sender=User)
def create_related_profile(sender, instance, created, *args, **kwargs):
if instance and created:
instance.profile = Profile.objects.create(user=instance)

最后更新我的 users/init.py 文件:

from django.apps import AppConfig


class UsersAppConfig(AppConfig):
name = 'django.users'
label = 'users'
verbose_name = 'Users'

def ready(self):
import users.signals

default_app_config = 'django.users.UsersAppConfig'

最后的更新是我相对不熟悉的。我怀疑这就是我的问题所在。

我可以通过 api 调用拒绝新用户,没有任何问题,但是,当我测试该新用户是否存在 Profile 对象时,出现以下错误:

python manage.py shell

from users.models import CustomUser

u = CustomerUser.objects.last()

u
<CustomUser:testuser@gmail.com> --- everything works to this point

u.profile --- this is where it breaks down

我在 shell 中留下了这个错误:

users.models.CustomUser.profile.RelatedObjectDoesNotExist: CustomUser has no profile.

如有任何帮助,我们将不胜感激,谢谢!

最佳答案

我认为你的错误在于你的信号方法:

from django.db.models.signals import post_save
from django.dispatch import receiver

from conduit.apps.profiles.models import Profile

from .models import User # you have CustomUser but you are calling User

@receiver(post_save, sender=User)
def create_related_profile(sender, instance, created, *args, **kwargs):
if instance and created: # you should only have created because you want this happen only when it is created
instance.profile = Profile.objects.create(user=instance)

此外,我认为无需更新用户 init.py

关于python - Django models.py OneToOneField --- 帮助创建两个模型之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53491350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com