保存时 Django 用户配置文件内联创建完整性错误

标签 django django-admin django-authentication

我目前在 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 的复选框时,它之前是如何工作的?另外,我该如何解决这个问题?

最佳答案

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

 UserProfile.objects.get_or_create(user=instance)

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

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

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

关于保存时 Django 用户配置文件内联创建完整性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6709351/

相关文章:

针对 LDAP 的 Django 用户身份验证 - 多个组

django - django 中应用程序的媒体路径

python - 模板内的 Django Cookie 值

python - 将数据发布到 django 管理表单

django - 如何强制保存 "empty"/未更改的 django 管理内联?

python - 如果已经有django项目,如何使用startproject(django-admin.py)?

python - 如何在views.py中调用django自定义编写的AuthenticationBackend的authenticate()方法?

django - 如何检测来自不同位置的 Django Web 应用程序的多次登录?

python - django 无法通过套接字连接到本地 MySQL 服务器 '/var/run/mysqld/mysqld.sock

python - Django 1.11 TypeError 上下文必须是 dict 而不是 Context