xaos_xv
xaos_xv

Reputation: 769

Django Rest Framework - Serializer validation doesn't work

I have simple serializer in my serializers.py and I want to validate one of the fields using validate(self, data) but it doesn't work.

Here is my code:

class DataUpdateSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate(self, data):
        if data['username'] != 'test':
            raise serializers.ValidationError('Wrong username')
        return data

I don't know if it will help but here are my views.py

class DataUpdateAPI(views.APIView):
    serializer_class = DataUpdateSerializer

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('pass')

        return Response("Just test response")

I don't know what's wrong with this code. Thanks in advance for the help!

Upvotes: 5

Views: 6871

Answers (2)

Andrei Berenda
Andrei Berenda

Reputation: 1986

At first, you should not use request.POST insted of it you should use, request.data(it is more usefull)

Also you should not use views.APIView, you should use generics.UpdateAPIView (because you are update fields)

But I do not undestend what you want to do? DO you want to update test users password?

You should use serializer in your post function

def post(self, request)
    data = request.data
    serializer = DataUpdateSerializer(data=data)
    if serializer.is_valid():
       return Response("all right")
    return Response(data=serializer.errors)

Upvotes: 2

hoefling
hoefling

Reputation: 66171

APIView is a low-level view class that doesn't use serializer_class attribute. If you want to use it, you have to instantiate and invoke the serializer yourself:

import rest_framework

class DataUpdateAPI(views.APIView):

    def post(self, request):
        serializer = DataUpdateSerializer(data=request.data)
        if serializer.is_valid():
            # do smth with serializer.data, it's valid now
            return Response("Just test response")
        return Response(serializer.errors, status=rest_framework.status.HTTP_400_BAD_REQUEST)

If you want more high-level usage, the invocation of serializer_class is implemented in GenericAPIView and subclasses. For example, CreateAPIView already implements the post method with deserializing and validation, so you don't have to reinvent the wheel:

class DataUpdateSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate(self, data):
        if data['username'] != 'test':
            raise serializers.ValidationError('Wrong username')
        return data

    def create(self, validated_data):
        print('my data is already validated here', validated_data)


class DataUpdateAPI(rest_framework.generics.CreateAPIView):
    serializer_class = DataUpdateSerializer

Upvotes: 7

Related Questions