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