Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework. Update gets an empty validated_data

I made the serializer below. When I use POST for creating or GET for getting instance, then all right. But when I use PATCH method for updating an instance, then update method gets an empty dict as validated_data. What is reason of this? If I use a fundamentally wrong approach, please show me right way. Thanks!

class UserSerializer(serializers.ModelSerializer):
    # password = serializers.CharField(write_only=True)

    class Meta:
        model = get_user_model()
        fields = ('id', 'email', 'first_name', 'last_name', 'password', )
        read_only_fields = ('is_staff', 'is_superuser', 'is_active', )
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password')
        user = self.Meta.model(**validated_data)
        user.set_password(password)
        user.is_active = True
        user.save()
        return user

    def update(self, instance, validated_data):
        print validated_data  # returns {} - empty dict
        return instance

I use ModelViewSet as view:

class UserViewSet(viewsets.ModelViewSet):
    queryset = get_user_model().objects.all()
    serializer_class = UserSerializer

urls.py:

router = routers.DefaultRouter()
router.register(r'accounts', UserViewSet, base_name='User')

urlpatterns = [
    url(r'', include(router.urls)),
]

For testing I use the Pycharm REST Client and send "first_name=Name" as request parameter for PATCH /accounts/1/ The print on serializer above shows me "{}". Needed account is exist and the serializer receives the target instance.

like image 440
Alexander Yudkin Avatar asked Oct 31 '22 05:10

Alexander Yudkin


1 Answers

Ok, I found a solution for your case. I actually hadn't used this tool before, although I have been using PyCharm for more than a year now. It is a great tool, but there is not much doc about the details. Solution:

  • First, we need to send the request as JSON (Content-Type: application/json) on the request, take a look here, it is well explained there how to do it.
  • Second, on the third column Request Body select the option Text and set the data with this structure {"first_name": "Name"} (it was the harder part for me).

For more details check this screenshot I'm attaching below:

enter image description here

like image 180
Vladir Parrado Cruz Avatar answered Nov 15 '22 09:11

Vladir Parrado Cruz