[Python] Failed to load resource: the server responded with a status of 401 (Unauthorized) -...

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    Am facing a crisis in my authentication system, during registration some of the fields like first and lastname, password, etc are not stored in the database which makes the login attempts return a 401 error, I have also tested with postman and in preview it shows invalid credentials. I have put a print statement in my registerView class to check if all the data fields reach the backend and it shows that indeed they do

    # Register User
    class RegisterView(APIView):
    permission_classes = [AllowAny]
    def post(self, request):
    print("Incoming Data from React:", request.data)
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
    user = serializer.save()
    return Response({"message": "User registered succefully"}, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


    The print statement in the register view class shows this data.

    Incoming Data from React: {'FirstName': 'Baker', 'lastName': 'Amos', 'username': 'baker', 'email': 'suubikaneb4@gmail.com', 'password': '1234', 'confirm_password': '1234', 'role': 'student', 'student_number': '24/U/26049/EVE', 'course_name': 'Computer Science', 'subject_taught': '', 'college': 'computing_and_informations', 'department': 'computer_science', 'lecture_number': ''}


    And this is how data is stored in the database;

    {'id': 14, 'password': '', 'last_login': None, 'is_superuser': False, 'username': 'baker', 'first_name': '', 'last_name': '', 'email': 'suubikaneb4@gmail.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2025, 3, 11, 9, 25, 44, 136188, tzinfo=datetime.timezone.utc), 'role': 'student', 'student_number': None, 'course_name': None, 'college': 'computing_and_informations', 'Lecture_number': None, 'subject_taught': None, 'department': 'computer_science'}


    As you can see the first and last name, password and other fields are all empty.

    I have tried to play with my register serializer class which i believe might be causing the issues just to ensure that the missing fields can also be saved to the database but still not achieving results

    class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
    model = User
    fields = [
    'first_name', 'last_name', 'username', 'email', 'password', 'confirm_password', 'role',
    'student_number', 'course_name', 'college',
    'lecture_number', 'subject_taught', 'department'
    ]
    extra_kwargs = {
    'password': {'write_only': True},
    'confirm_passwaord': {'write_only': True}
    }

    def validate(self, data):
    if data['password'] != data['confirm_password']:
    raise serializers.ValidationError({"password": "Passwords do not match."})

    role = data.get('role')

    if role == 'student':
    if not all([data.get('student_number'), data.get('course_name'), data.get('college')]):
    raise serializers.ValidationError(
    {"student_info": "Students must provide student number, course name, and college."}
    )

    elif role == 'lecturer':
    if not all([data.get('lecture_number'), data.get('subjects_taught'), data.get('department')]):
    raise serializers.ValidationError(
    {"lecturer_info": "Lecturers must provide lecturer number, subjects taught, and department."}
    )

    elif role == 'academic_registrar':
    if not data.get('college'):
    raise serializers.ValidationError(
    {"academic_registrar_info": "Academic Registrars must belong to a college."}
    )

    elif role == 'admin':
    if not data.get('college'):
    raise serializers.ValidationError(
    {"admin_info": "Administrators must be assigned to a college or the university."}
    )

    return data

    def create(self, validated_data):
    validated_data.pop('confirm_password') # Remove confirm_password before saving

    # Ensure first_name & last_name are properly extracted
    first_name = validated_data.pop('first_name', '')
    last_name = validated_data.pop('last_name', '')

    validated_data['password'] = make_password(validated_data['password']) # Hash the password
    user = User.objects.create(**validated_data, first_name=first_name, last_name=last_name)

    return user


    My user serializer looks like this:

    class UserSerializer(serializers.ModelSerializer):
    class Meta:
    model = User
    fields = ['id', 'username', 'email', 'role', 'college', 'department']


    Fellows please do help if you can

    Continue reading...

Compartilhe esta Página