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?
This commit is contained in:
andrewdodd 2015-10-01 11:13:03 +02:00
parent 689afd83cc
commit 4edf446692

View File

@ -108,6 +108,7 @@ class NestedBoundField(BoundField):
def as_form_field(self): def as_form_field(self):
values = {} values = {}
if self.value:
for key, value in self.value.items(): for key, value in self.value.items():
if isinstance(value, (list, dict)): if isinstance(value, (list, dict)):
values[key] = value values[key] = value