from djoser.serializers import UserSerializer as BaseUserSerializer from django.core import exceptions as django_exceptions from rest_framework import serializers from accounts.models import CustomUser from rest_framework.settings import api_settings from django.contrib.auth.password_validation import validate_password # There can be multiple subject instances with the same name, only differing in course, year level, and semester. We filter them here class CustomUserSerializer(BaseUserSerializer): course = serializers.ChoiceField( choices=CustomUser.COURSE_CHOICES, allow_blank=True, allow_null=True) section = serializers.CharField(allow_blank=True, allow_null=True) class Meta(BaseUserSerializer.Meta): model = CustomUser fields = ('id', 'username', 'email', 'first_name', 'course', 'section', 'last_name', 'is_teacher', 'is_technician') read_only_fields = ('id', 'username', 'email', 'is_teacher', 'is_technician') class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) email = serializers.EmailField(required=True) course = serializers.ChoiceField( choices=CustomUser.COURSE_CHOICES, allow_blank=True, allow_null=True) section = serializers.CharField(allow_blank=True, allow_null=True) password = serializers.CharField( write_only=True, style={'input_type': 'password', 'placeholder': 'Password'}) class Meta: model = CustomUser # Use your custom user model here fields = ('username', 'email', 'password', 'course', 'section', 'first_name', 'last_name') read_only_fields = ('email', 'is_teacher', 'is_technician') def validate(self, attrs): user = self.Meta.model(**attrs) password = attrs.get("password") try: validate_password(password, user) except django_exceptions.ValidationError as e: serializer_error = serializers.as_serializer_error(e) raise serializers.ValidationError( {"password": serializer_error[api_settings.NON_FIELD_ERRORS_KEY]} ) return super().validate(attrs) def create(self, validated_data): user = self.Meta.model(**validated_data) user.set_password(validated_data['password']) user.save() return user class ClearanceSerializer(serializers.Serializer): cleared = serializers.CharField() uncleared_transactions = serializers.IntegerField()