gpt4 book ai didi

python - django 在创建用户时在 userprofile 表中创建一行

转载 作者:搜寻专家 更新时间:2023-10-30 19:47:43 25 4
gpt4 key购买 nike

我正在按照这个(https://www.django-tips.com/tutorial/django-tutorial-with-twitter-app/1/?page=3)教程使用 Django 创建一个 Twitter 克隆应用程序。但是在项目中,用户会通过django默认的用户创建系统来创建。

问题是,我想在创建用户时在 userprofile 表中创建一行。否则,用户正在创建,我必须将其插入用户配置文件表中,然后才能访问项目的管理部分。我该怎么做?

模型看起来像这样:

from django.contrib.auth.models import User

class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
relation = models.ManyToManyField(
'self',
through='Relation',
symmetrical=False,
related_name='related_to',
default=None
)
def __unicode__(self):
return self.user.get_full_name()

class Relation(models.Model):
follower = models.ForeignKey(UserProfile, related_name='follows')
is_followed = models.ForeignKey(UserProfile, related_name='followers')
follow_time = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
return '%s follows %s' % (self.follower.user.username, self.is_followed.user.username)

class Meta:
unique_together = ('follower', 'is_followed')

而且教程中也提到了创建一个信号,但是他们还没有清除这个文件将在哪里创建,所以我按照官方文档创建了 signals.py 文件。

def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=user)
post_save.connect(create_profile, sender=User)

所以,我卡在了这个阶段,无法前进。提前致谢。

最佳答案

您不必创建信号文件...就在 UserProfile 之后

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

class UserProfile(models.Model):
....

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)

关于python - django 在创建用户时在 userprofile 表中创建一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724128/

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