8👍
Using settings.AUTH_USER_MODEL will load the user class lazily after all django apps are loaded. Calling get_user_model() on a module level when your app is initially loaded may result in that the user model app is not loaded and also circular imports.
Update: I read two specific questions:
How to correctly access the user model, contrib or custom.
Djangos get_user_model() is quite simply a call to django.apps get_model() using the settings.AUTH_USER_MODEL
. If you are writing apps that might be reused in other projects with other user models, use the get_user_model call. Always. Then it doesn’t matter what the user model is.
If you have created your own core.User
model and is very confident that your code will only be used in this project, from core.models import User
works as well.
When to use the string representation from settings instead of fetching the model.
The string representation will in the end usually call the same django.apps get_model() anyway. By giving a string instead of the class itself in Foreignkeys, OneToOneFields etc you simply don’t require the model to be looked up during django app imports, where the user model may not yet be available. So using string representation is simply deferred loading of a model. The same goes for all models.
An also during djangos different major versions this behavior have changed, which is another topic. Notice that get_user_model() have been updated in Django 1.11 for import usage.
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#referencing-the-user-model
5👍
you can go with get_user_model
instead User
from django.contrib.auth import get_user_model
User = get_user_model()
get_user_model
will Returns the User model that is active in this project.
if you modify(adding new field into it) default User
table you need to use get_user_model
it will return active User table.
BTW User
will return native from django.contrib.auth.models
- [Django]-Django group query by day with timezone specification
- [Django]-TemplateDoesNotExist in project folder django 1.8
- [Django]-DJANGO: Change field size of ModelMultipleChoiceField?