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

标签 python django database django-models user-profile

我正在按照这个(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/

相关文章:

python - tensorflow ,凯拉斯。使用 bool 数组作为输入构建模型

Python、Zeep 对 Pandas 的回应

django - 模块 "django.core.context_processors"未定义 "auth"可调用请求处理器

python - Django pip安装mysqlclient错误

javascript - 配方/ Material list MySQL 查询

c# - 如何在 Visual Studio 2010 的数据库中包含图像

python - 如何在 DJANGO 中为动态创建的 URL 设置 URL 别名?

python - aiohttp 帖子的当前上传步骤

python - 无法在终端中使用 pip 或 easy_install 在 Mac 上安装

database - Haskell persistent w/esqueleto : read entire table, 和计数记录