【发布时间】: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