Tuesday, June 25, 2019

I cannot register an extend user model of django

Hi

I got stuck in extending Django User Model.

 

This is my models.py:

class CustomUser(AbstractUser):
    USER_TYPE_CHOICES = ((
1, 'student'),
                        
(2, 'professor'),)
    username = models.CharField(
max_length=50, unique=True)
    user_type = models.PositiveSmallIntegerField(
choices=USER_TYPE_CHOICES, null=True)
    first_name = models.CharField(
max_length=50)
    last_name = models.CharField(
max_length=100)
    identity_no = models.PositiveIntegerField(
default=0)
    email = models.EmailField(
max_length=300,
                             
validators=[RegexValidator
                                          (
regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$",
                                          
message='please enter the correct format')],
                             
)
    date_joined = models.DateTimeField(
'date joined', default=timezone.now)
    is_active = models.BooleanField(
default=True)
    is_admin = models.BooleanField(
default=False)
    is_staff = models.BooleanField(
default=False)


class Student(models.Model):
    user = models.OneToOneField(CustomUser
, on_delete=models.CASCADE)
    entry_year = models.PositiveIntegerField()
    student_no = models.PositiveIntegerField()

 

my serializers.py:

class CustomUserSerializer(serializers.ModelSerializer):
   
class Meta:
        model = CustomUser
        fields = (
'first_name',
                 
'last_name',
                 
'identity_no',
                 
'email')

   
def create(self, validated_data):
       
"""
            Create and return a new `Professor user` instance, given the validated data.
        """
        
return CustomUser.objects.create(**validated_data)


class StudentSignUpSerializer(serializers.ModelSerializer):
    user = CustomUserSerializer()
# using another serializer in this serializer to access into CustomUserSerializer Fields

   
class Meta:
        model = Student
        fields = (
'user',
                 
'entry_year',
                 
)

   
def create(self, validated_data):
       
"""
            Create and return a new `Professor user` instance, given the validated data.
        """
       
return Student.objects.create(**validated_data)

my Views.py


class UserViewSet(CreateAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = CustomUserSerializer


class StudentSignUp(CreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSignUpSerializer

 

And the error is as follow:

No comments:

Post a Comment