DEV Community

Discussion on: User registration and authorization on a django API with djoser and JSON web tokens.

Collapse
 
lewiskori profile image
Lewis kori • Edited

hey Fmesteban,
really happy you found this post helpful.

One way you can approach this is by extending the Django AbstractUser model and introducing a field by the name role.

from django.contrib.auth.models import AbstractUser

TEACHER = 'Teacher'
STUDENT = 'Student'

ROLES = [(TEACHER, 'Teacher'), (STUDENT, 'Student'),]

class UserAccount(AbstractUser):
    role = models.CharField(max_length=10,choices=ROLES, default=STUDENT)

From this, you can make different UserProfiles like indicated from the post. For instance:

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class TeacherProfile(models.Model):
    user=models.OneToOne(User,limit_choices_to={'role':'Teacher'}, on_delete=models.CASCADE,related_name="teacher_profile")
    # your custom fields for teacher model

    def __str__(self):
        return self.user.username

class StudentProfile(models.Model):
    user=models.OneToOne(User,limit_choices_to={'role':'Student'}, on_delete=models.CASCADE,related_name="student_profile")
    # write your custom fields for student profile from here.

    def __str__(self):
        return self.user.username

After that has been set up, you'll just make a post_save signal that listens to the type of role on the new UserAccount instance. If it's a teacher, initialize TeacherProfile instance and populate it.

This can be achieved in a multistep form. Same for the student profile.

Collapse
 
fmesteban profile image
fmesteban

Thanks for the quick response! I had about the same idea but wanted to make sure that was the way to go.

Thanks again!

Thread Thread
 
lewiskori profile image
Lewis kori • Edited

You're welcome :)

Thread Thread
 
chafikmaouche profile image
Chafik Maouche

sir i want to use this role choice in the login process hwo can i do ti ?