Django 1.11 - 配置文件模型,1-1链接到用户模型

时间:2018-04-09 05:49:54

标签: python django

我尝试按照此blog post中的说明创建个人资料模型(用户模型的1-1链接)。但是发生了一些奇怪的事情:当我创建一个新用户时,Profile模型(通过信号)为用户生成相应的配置文件。但是,它为给定的user_id(在用户模型中为Django分配的id)生成两个配置文件。这两个配置文件完全相同,只是一个是明确定义的整数id,一个是None(请参见下图)。 screenshot

我用Google搜索,但仍然无法弄清楚这是怎么发生的。

非常感谢任何帮助!

编辑:2018-04-10

这是我的models.py(从https://simpleisbetterthancomplex.com修改)

# profiles/models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    # make a one-to-one conndection with User
    user = models.OneToOneField(User, on_delete = models.CASCADE)

    service1_expire = models.DateField(null=True, blank=True)
    product1_expire = models.DateField(null=True, blank=True)

    def __str__(self):
        return "%s" %self.user.username

    # extract username and email using functions
    # this is only for disply in Admin panel (so it cannot be used as a filter)
    def username(self):
        return self.user.username

    def email(self):
        return self.user.email

    def user_id(self):
        return self.user.id

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

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    #if not instance.is_superuser:  # add this, so I can login into django-admin
    instance.profile.save()

0 个答案:

没有答案