# Restframework validate fields

**URL:** https://forum.djangoproject.com/t/restframework-validate-fields/36048
**Category:** Forms & APIs
**Created:** [October 29, 2024, 12:50pm UTC](https://forum.djangoproject.com/t/restframework-validate-fields/36048 "2024-10-29T12:50:42Z")
**Posts on this page:** 5
**Page:** 1

<div class="post-metadata">

### Author: ![bosancero](https://avatars.discourse-cdn.com/v4/letter/b/f04885/32.png) [@bosancero](https://forum.djangoproject.com/u/bosancero)
#### Post date: [October 29, 2024, 12:50pm UTC](https://forum.djangoproject.com/t/restframework-validate-fields/36048/1 "2024-10-29T12:50:42Z")

</div>

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

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

```

Views.py

```auto
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

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

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

```

---

<div class="post-metadata">

### Author: ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)
#### Post date: [October 29, 2024, 1:17pm UTC](https://forum.djangoproject.com/t/restframework-validate-fields/36048/2 "2024-10-29T13:17:07Z")

</div>

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](https://www.django-rest-framework.org/#support)

---

<div class="post-metadata">

### Author: ![massover](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/massover/32/1792_2.png) [@massover](https://forum.djangoproject.com/u/massover)
#### Post date: [October 29, 2024, 2:16pm UTC](https://forum.djangoproject.com/t/restframework-validate-fields/36048/3 "2024-10-29T14:16:29Z")

</div>

Have you gone through the [drf tutorial](https://www.django-rest-framework.org/tutorial/1-serialization/)?

1. what is the purpose of checking for `first_key == "email"`?
2. after calling [is\_valid](https://www.django-rest-framework.org/tutorial/1-serialization/#working-with-serializers), you get validated data from `serializer.validated_data`, not from `initial_data`
3. use serializer [validation](https://www.django-rest-framework.org/api-guide/serializers/#field-level-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)](https://www.django-rest-framework.org/community/3.0-announcement/#using-is_validraise_exceptiontrue)

---

<div class="post-metadata">

### Author: ![bosancero](https://avatars.discourse-cdn.com/v4/letter/b/f04885/32.png) [@bosancero](https://forum.djangoproject.com/u/bosancero)
#### Post date: [October 29, 2024, 6:58pm UTC](https://forum.djangoproject.com/t/restframework-validate-fields/36048/4 "2024-10-29T18:58:01Z")

</div>

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

---

<div class="post-metadata">

### Author: ![bosancero](https://avatars.discourse-cdn.com/v4/letter/b/f04885/32.png) [@bosancero](https://forum.djangoproject.com/u/bosancero)
#### Post date: [November 9, 2024, 11:35am UTC](https://forum.djangoproject.com/t/restframework-validate-fields/36048/5 "2024-11-09T11:35:15Z")

</div>

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

```auto
    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'})

```
