Search code examples
pythondjangodjango-modelsdjango-users

Django user accounts, extending accounts


I am trying to extend Django's user-accounts Account model to add to it a set of additional fields. The thing is that "Account" objects have a set of methods that check some parameters and I would like to re-use all that code. Therefore, the first thing that comes to my mind is to extend the Account class with my own class:

class snAccount(Account):

    account = models.OneToOneField(Account, related_name="sn_account", verbose_name=_("snAccount"))

    # Extra fields
    organization = models.CharField(_("language"), ...,  )    
    country = CountryField()

    @classmethod
    def create(cls, request=None, **kwargs):
        create_email = kwargs.pop("create_email", True)
        user = kwargs.pop("user", None)
        acc = Account.create(request, user=user, create_email=create_email)
        x_account = cls(**kwargs)
        #x_account.user = request.user
        x_account.save()
        return x_account

The problem is that every time I want to save this "extended" Account class, I get the following exception:

Exception Type:     IntegrityError
Exception Value:    (1048, "Column 'user_id' cannot be null")

If I add the user field directly to the extended account (uncommenting the line "#x_account.user = request.user" i get the following error:

Exception Type:     IntegrityError
Exception Value:    (1062, "Duplicate entry '1' for key 'user_id'")

I thought that this field will be directly inherited from the Account model no explicit declaration of that Field is made. What am I doing wrong? Is this the correct way of doing it or would I better create a model that does not extend the Account class but still links to it through a ForeignKey field?


Solution

  • How to do this is well documented in the Django under Substituting a custom User model.