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. However, for supporting multiple roles with common sign up or login functionality, the framework requires us to relate with the Django 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 Django 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 Django custom 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. This helps us to build Django user login model for two users.

Read Also: 10 real-world Python Use Cases and Applications

An experienced Django development company like BoTree Technologies can help you build rapid Django apps with multiple user roles. Contact us today.

Consulting is free – let us help you grow!