django-rest-framework-bulk icon indicating copy to clipboard operation
django-rest-framework-bulk copied to clipboard

POST on Browsable API fails because of get_initial

Open jonathan-golorry opened this issue 8 years ago • 0 comments

The get_initial of a serializer normally looks like this:

def get_initial(self):
    if hasattr(self, 'initial_data'):
        return OrderedDict([
            (field_name, field.get_value(self.initial_data))
            for field_name, field in self.fields.items()
            if (field.get_value(self.initial_data) is not empty) and
            not field.read_only
        ])
     
    return OrderedDict([
        (field.field_name, field.get_initial())
        for field in self.fields.values()
        if not field.read_only
    ])

This breaks with AttributeError: 'list' object has no attribute 'get' if initial data is a list, such as after a POST on the browsable api (using the raw data tab to submit multiple objects).

I've fixed this in my code by switching get_initial on BulkSerializerMixin to:

def get_initial(self):
    return OrderedDict([
        (field.field_name, field.get_initial())
        for field in self.fields.values()
        if not field.read_only
    ])

A better solution might be to not set initial_data during a POST, but this was easier for me to find.

jonathan-golorry avatar Jul 07 '17 00:07 jonathan-golorry