保存时Django用户配置文件内联创建完整性错误
我目前在Django的用户配置文件中遇到一些问题 我按照建议创建了一个用户配置文件:保存时Django用户配置文件内联创建完整性错误,django,django-admin,django-authentication,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
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)
当我去添加一个新用户时,问题就出现了。在添加学校字段之前,我能够填写所有内容,这将非常有效。添加school字段后,我得到一个IntegrityError,它声明userprofile.school\u id不能为null。我哪里出了问题
我相信问题在于学校的选择并没有传递给get_或_create,所以当它去创建UserProfile时,它什么也看不到。那么,在单击is_教师复选框之前,它是如何工作的?还有,我该如何解决这个问题呢?是的,学校的选择没有通过,这里没有通过:
UserProfile.objects.get_or_create(user=instance)
您只需设置一个用户,并尝试创建配置文件
将null=True,blank=True
添加到学校字段,或者找出学校选择是什么,并将其传入:
UserProfile.objects.get_or_create(user=instance, school=school)