Anuj TBE
Anuj TBE

Reputation: 9806

extending default User model in Django

I've written my first application Django 2.0.

Everything is working fine and the application is almost ready when I realized to replace id primary key field from default integer type to UUID to make database entry more secure.

When I searched for this how to change id of user table to UUID I got many tutorials extending AbstractBaseUser.

Here is I have written own User model.

account/models.py

class User(AbstractBaseUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

But I'm confused more with examples on different sources.

Every example is adding few more fields in extended model like

first_name
last_name
is_staff
is_admin
active

and functions as

def get_fullname(self):
def get_shortname(self):
etc.

I think all these fields and functions are there by default in AUTH_USER_MODEL.

Does extending AbstractBaseUser overwrites AUTH_USER_MODEL and it is required to add all fields which is there by default?

also, I'm using settings.AUTH_USER_MODEL as foreign key in different models. Should It be replaced by account.User model?

I'm also using django-allauth plugin to enable login using the social network and use email only for authentication. Do I require to add email field in the extended model with unique=True?

Upvotes: 2

Views: 1072

Answers (2)

Mike Robinson
Mike Robinson

Reputation: 8995

As the Django documentation indicates, it's difficult to extend the User table after-the-fact, and not recommended at all for apps. A better way is to create an auxiliary table which has a 1:1 relationship with the user-id. Leave Django's user-table alone and just use this other table to pony-up to it.

The "Django Annoying" project, at https://github.com/skorokithakis/django-annoying#autoonetoonefield, has some very useful "juice" to make this much easier: an AutoOneToOneField. Whereas Django's foreign-key field will throw an error if an record doesn't exist, this field will automagically create one on-the-fly, thereby side-stepping the entire issue. (The documentation page linked-to above shows exactly how this is done.)

Upvotes: 0

neverwalkaloner
neverwalkaloner

Reputation: 47374

Django AbstractBaseUser provides only following fields: password, last_login, is_active. So if you are using custom User model inherited from AbstractBaseUser you need to define all other fields such as email manually. As another part of question just adding AUTH_USER_MODEL = 'users.User' to your settings.py file should make everything works without replace code in your project.

UPD If you need field like first_name, last_name, etc. to be includet to the model you can use AbstractUser instead of AbstractBaseUser.

Upvotes: 2

Related Questions