djangodjango-modelsdjango-admindjango-usersdjango-admin-tools

DoesNotExist error when using custom User model


I have a Group model in my group/models.py file:

class Group(models.Model):
   leader = models.ForeignKey(User, on_delete=models.CASCADE)
   name = models.CharField(max_length=55)
   description = models.TextField()
   joined = models.ManyToManyField(User, blank=True)

and an Account model, which is an extension of django's standard User, in users/models.py:

class Account(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    joined_groups = models.ManyToManyField(Group, related_name='joined_group')
    created_groups = models.ManyToManyField(Group)

in users/admin.py:

class AccountInline(admin.StackedInline):
    model = Account
    can_delete = False
    verbose_name_plural = 'Accounts'

class CustomUserAdmin(UserAdmin):
    inlines = (AccountInline,)

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

The issue I'm having trouble understanding is when I create a new User, the Account for that User doesn't seem to really be registering. At the bottom of the new User's page (via django admin site) the new Account looks like this:

new User admin page

Now, this new User seems to have an account which contains joined_groups and created_groups but when I try to join or create a Group with that new User, I get an error DoesNotExist - Account matching query does not exist

I'm not sure why the new User/Account isn't really registering its Account. In comparison, inside my AdminUser page its Account info looks like this:

Admin User admin page

Account: #1 for the new User vs. Account: Acount object (6) for Admin User.

Finally, when I go onto the django admin site and add my new User to a Group and hit save, Account: #1 changes to Account: Acount object (7) which then allows the new User to create and join other Groups.

I'm completely lost on what is happening and why it is. It's important because I want new Users who register to be able to join and create Groups with an admin starting them off. Did I mess up my Account model? Or is this something to do with django's general User model? Or is it something else entirely?


Solution

  • Basically you have two models connected by a relationship, but I can't see the code for creating an account object. It is a good practice to create a user-related profile with the post_save signal.

    from django.contrib.auth.models import User
    from django.dispatch import receiver
    from django.db.models.signals import post_save
    from .models import Account
    
    @receiver(post_save, sender=User)
    def create_save_account(sender, instance, created, **kwargs):
        if created:
            Account.objects.create(user=instance)
            instance.account.save()
    

    In addition, I refer to the documentation and examples.