[Fixed]-User Profile not saving profiles and throwing exceptions

1đź‘Ť

âś…

Seconding what itzmeontv said about the inheritance AND one-to-one being redundant. As the documentation references, you can extend user model functionality by either using a one-to-one relationship, or by making a model that inherits from the built-in user model. One of the issues here is that you’re doing both of those things, which is unnecessary and may lead to confusion down the road.
https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model

Regarding your specific error, the issue is coming about because you’re trying to create a user object that has a username which already exists. The “user” that you’re trying to create is actually the “admin_profile” object which has a non-unique username.

I’d imagine that this particular issue would resolve itself by having class Profile inherit from models.Model rather than from User.

from django.db import models

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    chunks = models.ManyToManyField(Chunk)

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()

Leave a comment