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.
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:
JSON
(Content-Type: application/json
) on the request, take a look here, it is well explained there how to do it.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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With