Friday, December 11, 2015

Duplicate entry error with the Django's User Profile model

I wrote a User Profile model which extends the Django's User authentication model as following:

class TeacherProfile(models.Model):
    user = models.OneToOneField(User, related_name="teacher_profile", \
    teacher_number = models.CharField(max_length=255, blank=True, null=True) # Office
    desc = models.CharField(max_length=255, blank=True, null=True) # Description
    title = models.CharField(max_length=255, blank=True, null=True)
    school = models.ForeignKey('School', null=True, 

    def __unicode__(self):
      return '<TeacherProfile %s>' % self.teacher_number

# auto create teacher profile the first time student log-in
def create_teacher_profile(sender, instance, created, **kwargs):
    if created:
        new_profile = TeacherProfile.objects.create(user=instance)
        user = LDAPBackend().populate_user(instance.username)
        if user:
            desc = ''
            if user.ldap_user.attrs.get("description", []):
                desc = user.ldap_user.attrs.get("description", [])[0]

            office = ''
            if user.ldap_user.attrs.get("physicalDeliveryOfficeName", []):
                office = user.ldap_user.attrs.get("physicalDeliveryOfficeName", [])[0]

            title = ''
            if user.ldap_user.attrs.get("title", []):
                title = user.ldap_user.attrs.get("title", [])[0]

            new_profile.teacher_number = office
            new_profile.desc = desc
            new_profile.title = title

post_save.connect(create_teacher_profile, sender=User)

But every time I try to add a new user in Django's admin dashboard, I got the Duplicate Entry error. What I did to get rid of the error is by adding the "primary_key=True" parameter to the user field:

user = models.OneToOneField(User,..., primary_key=True