In order to link HOD with particular department, lets create a new model named HodProfile to store the hod's department as well as some other information.
Create a model in authentication/models.py
file.
class HodProfile(models.Model):
hod = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
office_number = models.CharField(max_length=25)
faculty_code = models.CharField(max_length=10)
def __str__(self):
return f"{self.hod}"
This stores the hod's detail along with the User model with a one-to-one field, and the department as a foreign key mapped with Hod. Along with this information, the office number and faculty code are taken.
Now, you can run the migrations to make changes in the database.
python manage.py makemigrations
python manage.py migrate
This creates another table and we can continue to register this model in admin page.
Inside authentication/admin.py
:
@admin.register(HodProfile)
class HodProfileAdmin(admin.ModelAdmin):
list_display = ('hod', 'department', 'office_number', 'faculty_code')
search_fields = ('office_number', 'faculty_code')
list_filter = ('department',)
Now HodProfiles can be created by admin through the admin page in Django.
Clicking on the save button will generate a faculty profile, for the particular user.
Here, while addition of HodProfile, for now only 2 users are there so its easier to select through dropdown.
But as the number of Users increases, this list will also increase. At that point it will be difficult to create particular Hod Profiles. In that case another variable may be added inside the admin class autocomplete_fields
, This will allow a search option to easily select the user.
@admin.register(HodProfile)
class HodProfileAdmin(admin.ModelAdmin):
list_display = ('hod', 'department', 'office_number', 'faculty_code')
search_fields = ('office_number', 'faculty_code')
list_filter = ('department',)
autocomplete_fields = ('hod', 'department')
After doing this change, the admin site will be like this. This make it easier for selecting users. Further in this we will see how hod's or admin can add events.