Supporting Multiple Roles Using Django’s User Model
We often have multiple roles in our Django web applications, and most of the time they have two common functionality of sign up and log in, others may completely vary based on the type of role.
Django provides a default User model which can handle sign up and log in functionality, but for supporting multiple roles with common sign up or login functionality requires us to relate with the User model in a different way.
Creating a One-To-One Link
Let us say we have two roles an Intern and an HR each having a distinct set of fields. We need to extend the User model and create two separate models for Intern and HR each with one to one relationship with the extended User model
Note that we have defined signals so that our Profile model gets created and updated whenever User model gets created or updated.
Now let us how to set our forms.py
Now in the template part, we shall be using two forms one for the User and the other for InternProfile the same applies in the case of HRProfile
Finally the view part. In the view we first need to create the user in User model so using signal Django automatically creates the instance of InternProfile, we add intern specific data like bio and location to this instance and finally, we save it.
Note that we have used related_name to access InternProfile fields from User instance.
In a similar fashion, we can create a view for HRProfile also.
At BoTree Technologies, we build enterprise applications with our Django team of 20+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management