[Fixed]-Django REST Framework browsable API error when using different serializers for different HTTP methods

1👍

The problems comes from the fact, that you break REST convention. Instead of resource representation you use action in PUT request. In the REST you would rather have is_accepted or state field inside your FriendRequest object and by modification of this field you would accept or reject requests. I highly recommend you to point on this to designers of your spec.

In the browsable API DRF generates a form to update record, so it gets serializer by calling get_serializer() (which returns AcceptRejectSerializer) and transforms this serializer into form. Then it gets record by calling get_object() (which returns FriendshipRequest object) and tries to fill form with data got from the record. Obviously fields in record and serializer doesn’t match, so you get an error.

As a shitty solution you can add accept attribute inside get_object() method:

def get_object(self):
    sender = generics.get_object_or_404(get_user_model(),
            pk=self.kwargs['pk'])
    obj = generics.get_object_or_404(FriendshipRequest, 
            from_user=sender,
            to_user=self.request.user)

    self.check_object_permissions(self.request, obj)

    obj.accept = False

    return obj

Or add it as into FriendshipRequest model:

class FriendshipRequest(...):
    # ...

    accept = False

Or you can try to override view to skip form filling step.

Leave a comment