Kakar
Kakar

Reputation: 5609

How to update an object in Django rest framework

I have a custom user model, and have its model seriazer to with. Its modelviewset also works in displaying the user list.

class UserSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True, style={'input_type': 'password'})
    password2 = serializers.CharField(write_only=True, style={'input_type': 'password'})
    mobile = serializers.IntegerField()

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'email', 'mobile', 'password1', 'password2')

    def validate(self, data):
        if data['password1'] != data['password2']:
            raise serializers.ValidationError({'password1': 'Both password must be equal.'})
        return data

    def create(self, validated_data):
        if self.is_valid(True):
            return User.objects.create_user(
                validated_data.get('email'),
                validated_data.get('first_name'),
                validated_data.get('last_name'),
                validated_data.get('mobile'),
                validated_data.get('password1'),
            )

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

However, I am trying to update a User object by posting the model's fields and its value in json key value pair format in PUT http method.

{
    "first_name": "Some"
    "last_person": "name"
    "mobile": "0123456789" 
}

But this gives me a 400 bad request error:

{
    "password1": [
        "This field is required."
    ],
    "password2": [
        "This field is required."
    ],
    "email": [
        "This field is required."
    ]
}

How can I update an object with only the partial model fields?

Upvotes: 0

Views: 1110

Answers (2)

Matheus Veleci
Matheus Veleci

Reputation: 344

Serializer is considering this fields as obligatory, probably you are putting in your custom model null = False.

Upvotes: 0

Linovia
Linovia

Reputation: 20996

How can I update an object with only the partial model fields?

That's what PATCH is for as opposed to PUT. It'll pass the partial flag to the serializer will will bypass missing field's validation.

Upvotes: 0

Related Questions