How can I create custom user model for different user types using django rest framework

Viewed 2918

I am new to django rest framework and I want to create different types of users "I think it should be 4", (students, teachers, staff and admin) And I want the staff user to register the teacher and student users. I want to use custom user model and use email to register and login, can it be done, please help, I have been looking for days for anything that can help me to understand how to do it

2 Answers

You can use AbstractUser , This is pretty straighforward since the class django.contrib.auth.models.AbstractUser provides the full implementation of the default User as an abstract model.

**
    from django.db import models
    from django.contrib.auth.models import AbstractUser
    USER_TYPE_CHOICES = (
     ('student', 'student'),
     ('teacher', 'teacher'),
     ('staff', 'staff'),
     ('admin', 'admin'),
                        )
    class User(AbstractUser):
       user_type = models.CharField(max_length=40,choices=USER_TYPE_CHOICES)
**

After that you have to update our settings.py defining the AUTH_USER_MODEL property.

 AUTH_USER_MODEL = 'Your app name.User'

You can email as username in your serializers.py:

class RegisterSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True)

    class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 'password','password1',  'user_type',)

    def validate(self, attr):
       validate_password(attr['password'])
       return attr

    def create(self, validated_data):
          user = User.objects.create(
                username=validated_data['email'],
                user_type=validated_data['user_type'],
                email=validated_data['email'],
                first_name=validated_data['first_name'],
                last_name=validated_data['last_name'],

                )
        user.set_password(validated_data['password'])
        user.save()



       return user

Now ,you can use this serializer in your views.py and create user with different user types

Best regards,

Related