Failed to load resource: the server responded with a status of 401 (Unauthorized) - react & django
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
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)
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
Fellows please do help if you can