Reputation: 1475
I'm having some issues with user profiles in Django currently.
I followed the recommendations and created a user profile:
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)
I also inlined this user profile into my User admin page. This is what I use to make sure that a user profile is created along with a user:
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)
The issue arises when I go to add a new user. Before adding the school field, I was able to fill everything in and it would work great. After adding the school field, I get an IntegrityError that states that userprofile.school_id cannot be null. Where am I going wrong here?
I believe the issue is that the choice of school is not being passed to the get_or_create and so when it goes to create the UserProfile, it sees nothing. How then did it work before, when clicking the checkbox for is_teacher? Also, how would I go about fixing this?
Upvotes: 3
Views: 747
Reputation: 3531
Yes, the choice of school isn't getting passed, it's not getting passed here:
UserProfile.objects.get_or_create(user=instance)
You're only setting a user, and trying to create the profile.
Add null=True, blank=True
to the school field, or figure out what the school choice was, and pass that in:
UserProfile.objects.get_or_create(user=instance, school=school)
Upvotes: 2