From 4edf4466922a0ae5a3b26f8570cf54e652e7618c Mon Sep 17 00:00:00 2001 From: andrewdodd Date: Thu, 1 Oct 2015 11:13:03 +0200 Subject: [PATCH] Updated NestedBoundField as_form_field to handle None This fixes the html rendering of a nested bound field that is allowed to be null. For example, if my API has related model serialisers, sort of like this: class PersonSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Person fields = ('id', 'url', 'first_name', 'last_name') class GunSerializer(serializers.HyperlinkedModelSerializer): pointing_at = PersonSerializer(many=False, allow_null=True, required=False) class Meta: model = Gun fields = ('id', 'url', 'brand', 'pointing_at') The 'pointing_at' field becomes a NestedBoundField. The API works fine with the null reference in the 'json-only' form (i.e. ?format=json). However, when the HTML form tries to render, I get an error 'NoneType' object has no attribute 'items'. This change prevents the FOR loop from attempting to access .items() on the self.value when it is None. NB: This does not fix the issue with rendering the put-object-form correctly. Perhaps there should be a mechanism to allow the PrimaryKeyRelatedField HTML picker? --- rest_framework/utils/serializer_helpers.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py index ddf160868..d113881f1 100644 --- a/rest_framework/utils/serializer_helpers.py +++ b/rest_framework/utils/serializer_helpers.py @@ -108,11 +108,12 @@ class NestedBoundField(BoundField): def as_form_field(self): values = {} - for key, value in self.value.items(): - if isinstance(value, (list, dict)): - values[key] = value - else: - values[key] = '' if value is None else force_text(value) + if self.value: + for key, value in self.value.items(): + if isinstance(value, (list, dict)): + values[key] = value + else: + values[key] = '' if value is None else force_text(value) return self.__class__(self._field, values, self.errors, self._prefix)