Franchu
Franchu

Reputation: 473

Django REST framework non-model serializer and BooleanField

I seem to have hit a wall full of puzzling results when trying to deal with the following use case:

URL: '^api/event/(?P<pk>[0-9]+)/registration$'
payload: {"registered": "true"} or {"registered": "false"}

I retrieve the event object corresponding to the given pk, and then based on that I want:

Everything works fine until the point where I want to process the incoming payload in the PUT request. I've tried creating a serializer like this:

class RegistrationSerializer(serializers.Serializer):
    registered = fields.BooleanField()

and call it from an APIView's put method with:

serializer = RegistrationSerializer(data=request.DATA)

but it doesn't work and serializer.data always contains `{"registered": False}

From a shell I tried another isolated test:

>>> rs = RegistrationSerializer(data={'registered':True})
>>> rs
<app.serializers.RegistrationSerializer object at 0x10a08cc10>
>>> rs.data
{'registered': False}

What am I doing wrong? What would be the best way to handle this use case?

Upvotes: 2

Views: 1350

Answers (1)

Tom Christie
Tom Christie

Reputation: 33901

You need to call rs.is_valid() first, before accessing rs.data.

Really the framework ought to raise an exception if you don't do so.

Upvotes: 1

Related Questions