What is the minimal setup for a Django Custom User Model?

54 Views Asked by At

I would like to install, as recommended, a custom user model for a new project early in the process, to avoid complications in migrating further down the line.

But since the project is under development and acts as a testbed, I don't yet know which additional fields and methods I will require. I therefore want to get a custom user model up and running with the minimal required information so that the default registration (signup, login, etc) functions all work.

I used the following code, (in an app called 'accounts')

class User(AbstractUser):
    def __str__(self):
        return self.email

and in settings.py

AUTH_USER_MODEL = 'accounts.User'

I inherited from AbstractUser in order to obtain the default functionality, which seems to work.

However, the (default) signup produces the following error in the browser:

Manager isn't available; 'auth.User' has been swapped for 'accounts.User'

So it seems to me that I must also define a UserManager for the custom User.

Now there is much advice available about how to do this if additional functionality is required (eg make the email the username, supply extra fields, and so on).

But at this stage, I don't want any additional functionality. That will come later. At this point I simply want to ensure that users can sign up, login, change passwords, etc and I can then develop the logic of the rest of the programme. I can return to the customization when I have developed this logic at which point it will be clear what additional functionality, if any, is required of the User model.

The problem is therefore (I think) to define a UserManager for my custom User Model.

So I tried the following:

from django.contrib.auth.models import AbstractUser, UserManager
...
class User(AbstractUser):
    objects=UserManager()
    def __str__(self):
        return self.email

This however returns the same error:

Manager isn't available; 'auth.User' has been swapped for 'accounts.User'

Thus it seems I must also create a custom User Manager. Now, all the implementations I have seen require that such a user manager should inherit from BaseUserManager and implement at least create_user and create_superuser.

Is there some equivalent of 'AbstractUser' for the custom manager that allows me to simply get the default behaviour and customise later?

The nearest I've seen to a discussion of this matter is here

1

There are 1 best solutions below

4
ozgvr On

If you have any references to the User model (from django.contrib.auth) in somewhere else in the code , make sure to update them to point to the custom user model from the accounts app. If you already have updated AUTH_USER_MODEL in settings.py, you can use:

from django.contrib.auth import get_user_model
User = get_user_model()