User Models
Django provides a built-in user model with predefined fields and methods, including the following fields.
username
first_name
last_name
email
password
groups
user_permissions
is_staff
is_active
is_superuser
last_login
date_joined
You may want to add or select the required fields to the app you are developing. There are two primary ways to do it.
- Extending the user model
- Substituting the user model
1. Extending the user model – Profile model with OneToOne relationship
In your app, you may want to add more fields on top of the Django built-in user model, such as a user icon, mobile number, and other user profiles. Unless you intend to delete or modify a user authentication method, extending the user model may be easier.
The approach is to create an extended model using OneToOneField
. Create a new model (e.g., the UserProfile model) with a One-To-One relationship with the built-in user model.
Practice 1
Objective:
Extending the User Model (User Profile)
In this practice, we'll demonstrate how to extend the built-in user model by making a new UserProfile model that has a One-To-One relationship with the built-in user model.
1. Create a new app
As the UserProfile model is not related to any of the models under the employee_learning app, it is better to create a new app by running the startapp
command. We use 'users' as an app name this time.
python manage.py startapp user_profile
2. Add the app in settings.py
As the app is new, add it under INSTALLED_APPS
in settings.py.
INSTALLED_APPS = [
:
'user_profile',
:
]
3. Add the UserProfile model in models.py
Open models.py under the new app, and add the code below.
Subscribe now for
uninterrupted access.