【问题标题】:Django User Profile Inline Creation Integrity Error on Save保存时 Django 用户配置文件内联创建完整性错误
【发布时间】:2011-10-06 06:21:38
【问题描述】:

我目前在 Django 中遇到一些用户配置文件问题。

我遵循了建议并创建了用户个人资料:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    is_teacher = models.BooleanField(verbose_name = "Teacher", help_text = "Designates whether this user is a teacher and can administer and add students and classes")
    school = models.ForeignKey(School)

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

    def save(self, *args, **kwargs):
        if not self.pk:
            try:
               p = UserProfile.objects.get(user=self.user)
               self.pk = p.pk
           except UserProfile.DoesNotExist:
               pass

        super(UserProfile, self).save(*args, **kwargs)

我还将这个用户配置文件内联到我的用户管理页面中。这是我用来确保与用户一起创建用户配置文件的方法:

def create_user_profile(sender, instance, created, **kwargs):
"""Create the UserProfile when a new User is saved"""
    if created:
        print "User Profile Creation: ", created
        UserProfile.objects.get_or_create(user=instance)

当我去添加一个新用户时,问题就出现了。在添加学校字段之前,我能够填写所有内容,并且效果很好。添加学校字段后,我收到一个 IntegrityError,指出 userprofile.school_id 不能为空。我哪里错了?

我认为问题在于学校的选择没有传递给 get_or_create,因此当它创建 UserProfile 时,它​​什么也看不到。在单击 is_teacher 的复选框时,它之前是如何工作的?另外,我该如何解决这个问题?

【问题讨论】:

    标签: django django-admin django-authentication


    【解决方案1】:

    是的,学校的选择没有通过,这里没有通过:

     UserProfile.objects.get_or_create(user=instance)
    

    您只是在设置一个用户,并尝试创建配置文件。

    null=True, blank=True 添加到学校字段,或找出学校选择是什么,然后将其传递:

     UserProfile.objects.get_or_create(user=instance, school=school)
    

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 2017-11-13
      • 2012-07-14
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多