freecodeschoolindy/student-management-system

Adding is_student to UserSerializer | Masking password as a password field

Closed this issue · 0 comments

users/views.py:

from rest_framework import serializers, viewsets
from django.contrib.auth import get_user_model

class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
style={'input_type': 'password'}, write_only=True, min_length=8
)

class Meta:
    model = get_user_model()
    fields = ('id', 'email', 'password', 'is_student')
    # extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}

def create(self, validated_data):
    # is_student is a custom field in the User model so this field
    # needs to be saved AFTER the User is saved
    is_student = validated_data.pop('is_student')
    user = get_user_model().objects.create_user(**validated_data)
    user.is_student = is_student
    user.save()
    return user

class UserViewSet(viewsets.ModelViewSet):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer