Restframework validate fields

I’m new to Django and the Django REST framework, and I want to validate incoming requests to ensure that incorrect fields return a “bad request” response.

I’ve programmed a solution, but I think it could be improved. Can someone help me with a better way to validate fields in requests?

What I have done is here but I think there are way better solution

 first_key = next(iter(serializer.initial_data))
          if serializer.is_valid() and first_key == "email":

Views.py

class ResetPasswordView(generics.GenericAPIView):

    def post(self, request):
        serializer = ResetPasswordSerializer(data=request.data)
        first_key = next(iter(serializer.initial_data))
          if serializer.is_valid() and first_key == "email":

            email = serializer.initial_data['email']
            user = User.objects.filter(email=email).first()

            if user:
                token_generator = PasswordResetTokenGenerator()
                token = token_generator.make_token(user)

                # Insert new password reset object in db
                PasswordReset.objects.update_or_create(
                    user = user,
                    defaults= { 'token': token }
                )

                reset_url = f"{os.environ['PASSWORD_RESET_BASE_URL']}/{token}"

                # TODO: implement here to send an email

                return Response({'success': 'We have sent you a link to reset your password'}, status=status.HTTP_200_OK)
            else:
                return Response({"error": "User with credentials not found"}, status=status.HTTP_404_NOT_FOUND)

        else:
            return Response({"error": "Bad request"}, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class ResetPasswordSerializer(serializers.Serializer):
    email = serializers.EmailField(
        required=True,
    ),

    class Meta:
        model = PasswordReset
        fields = ['email']

Side note: This forum is not one of the official support channels for the Django REST Framework. While your question is welcome here, and there are some people here who try to help, you might get more assistance by using one of the resources identified at Home - Django REST framework

Have you gone through the drf tutorial?

  1. what is the purpose of checking for first_key == "email"?
  2. after calling is_valid, you get validated data from serializer.validated_data, not from initial_data
  3. use serializer validation to handle your check for the user. create a validate_email method that queries the database checking for a user. if the user does not exist for that email, you raise a validation error there, and then the framework will automatically return a 400 response if you use serializer.is_valid(raise_exception=True)

Thanks for tip I didn’t see that they have community. Next time I will write there instead

Hi @massover,
I figured out and made it so it works. Thanks for help

For others that struggle with same issue. Here is my solution

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data

        email = data['email']

        try:
            user = User.objects.get(email=email)
        except:
            raise ValidationError({'error': 'User with credentials not found'})