Hi
I'm trying to handle POST requests to my API endpoint using a different
serializer than the one used for GET or PUT requests. The format of the
POSTed messages is different from the Model and from GET/PUT and must be
pre-processed before storing to the database.
As a demo of my problem I made a very simple model and the corresponding
API view and serializer:
class Message(models.Model):
message = models.CharField(max_length = 500)
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = ('message',)
class MessageViewSet(viewsets.ModelViewSet):
queryset = Message.objects.all().order_by('-pk')
serializer_class = MessageSerializer
That works well. Then I tried to override the MessageViewSet.create() to
handle POST requests differently.
class MessageSerializer_FromTo(serializers.Serializer):
sender = serializers.EmailField()
recipient = serializers.EmailField()
def create(self, validated_data):
message = "Message from <{sender}> to <{recipient}>".format(**
validated_data)
return Message(message)
class MessageViewSet(viewsets.ModelViewSet):
queryset = Message.objects.all().order_by('-pk')
serializer_class = MessageSerializer
# Handle POST requests differently
def create(self, request, format=None):
message = MessageSerializer_FromTo(data = request.data)
if message.is_valid():
message.save()
return Response(message.data, status=status.HTTP_201_CREATED)
return Response(message.errors, status=status.HTTP_400_BAD_REQUEST)
Essentially I want to pass this JSON to POST /api/messages/
{"sender": "[email protected]", "recipient": "[email protected]"}
GET /api/messages/1/ should return
{"message": "Message from <[email protected]> to <[email protected]>"}
However the POST fails with this:
Internal Server Error: /api/messages/
Traceback (most recent call last):
File ".../rest_framework/fields.py", line 441, in get_attribute
return get_attribute(instance, self.source_attrs)
File ".../rest_framework/fields.py", line 100, in get_attribute
instance = getattr(instance, attr)
*AttributeError: 'Message' object has no attribute 'sender'*
During handling of the above exception, another exception occurred:
[...]
*AttributeError: Got AttributeError when attempting to get a value for
field `sender` on serializer `MessageSerializer_FromTo`.*The serializer
field might be named incorrectly and not match any attribute or key on the
`Message` instance.
*Original exception text was: 'Message' object has no attribute 'sender'.*[
26/Feb/2018 05:09:08] "POST /api/messages/ HTTP/1.1" 500 19059
This is just to demonstrate the problem obviously, I'm doing more complex
things in my POST handler, but the error is pretty much the same.
Any idea how to achieve this? I.e. accept POST fields that are completely
different from the Model fields?
Thanks!
Michael
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.