Using Custom User Model In Django¶
When we start a new project we have to use custom user model in django application. Because, django provides basic fields required for the user. We may require to add extra fields in the future. So, we have to use custom user model.
To implement the**custom user model in django** application we do not need to rewrite the model from the scratch. We can avoid it by inheriting the class AbstractUser
from django. we can import it like from django.contrib.auth.models import AbstractUser
. After writing the custom user model we have to add our custom user model to django project settings. We can do this by adding AUTH_USER_MODEL = 'myapp.User'
in project/settings.py.
using custom user model in django¶
# myapp/models.py
from django.contrib.auth.models import AbstractUser
def user_avatar_path(instance, filename):
return 'user_{0}/avatar/{1}'.format(instance.id, filename)
class User(AbstractUser):
avatar = models.ImageField(upload_to=user_avatar_path)
def __str__(self):
return self.username
# myproject/settings.py
# .......
# .......
AUTH_USER_MODEL = 'myapp.User'
When we inherit the "AbstractUser" model we get the fields like "first_name", "last_name", "email", "username", "password", "is_active", "is_superuser" by default. In the above code we have added the extra field "avatar" that will store a photograph of the user. We can also add user phone number, country, etc. We are using the existing code and enhancing it with new features. We can modify the "User" model in the future without affecting the existing functionality if it is required. It can be achieved only by using custom user model in django.
After pointing AUTH_USER_MODEL
in settings. Try to run commands "python manage.py makemigrations && python manage.py migrate
". When we run the command "makemigrations
", It will create migrations and when we run command "migrate
", ORM will convert these migrations into SQL queries and creates the tables.
References:
https://docs.djangoproject.com/en/2.0/topics/auth/customizing/