Django-rest框架:如何清除/清空与FormData的ManyToMany关系

时间:2014-10-16 06:00:35

标签: ajax django django-rest-framework

我正在通过django-rest-framework编辑Django用户实例,它运行良好,包括设置/更改组成员资格。 但我无法清除/清空所有组中的用户。

这适用于我在shell上使用httpie:

http -j PATCH :8000/api/accounts/user/1/  groups:='[]'

这是我在浏览器中尝试的内容:

var data = new FormData(); 
data.append('groups', JSON.stringify([])); // not working

$.ajax({
  dataType: 'json',
  url: '/api/accounts/user/1/',
  type: 'PATCH',
  processData: false, 
  contentType: false,
  data: data
});

表单数据如下:

------WebKitFormBoundaryJu7QPC8AcBTpWEKJ
Content-Disposition: form-data; name="groups"

[]

回复是:

{"groups": ["Incorrect type.  Expected pk value, received unicode."]}

1 个答案:

答案 0 :(得分:0)

我想问题是FormData无法传输像httpie这样的原始JSON。 restframework以不同的方式对待它们:

def field_from_native(self, data, files, field_name, into):
    ...
    if self.many:
        try:
            # Form data
            value = data.getlist(field_name)
            if value == [''] or value == []:
                raise KeyError
        except AttributeError:
            # Non-form data
            value = data[field_name]

这种自定义方法可以实现,但我仍然不喜欢这种方法。要清除我将null附加到FormData:

data.append('groups', null);

并将其列为后端的空列表:

class FormDataPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    """
     Custom PrimaryKeyRelatedField which allows clearing via form-data using
     JS's 'null' as to clearing value.
    """
    def field_from_native(self, data, files, field_name, into):
        data = dict(data)
        if self.many:
            if data.get(field_name) == [u'null']:
                data[field_name] = []

        super(FormDataPrimaryKeyRelatedField, self).field_from_native(data, files, field_name, into)


class UserSerializer(serializers.ModelSerializer):

    groups = FormDataPrimaryKeyRelatedField(many=True, source='groups', required=False)