I'm editing Django user instances via django-rest-framework, it works well, including setting/changing group membership. But I can't manage to clear/empty the user from all groups.
This works for me on the shell with httpie:
http -j PATCH :8000/api/accounts/user/1/ groups:='[]'
This is what I try within the browser:
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
});
The form data looks like:
------WebKitFormBoundaryJu7QPC8AcBTpWEKJ
Content-Disposition: form-data; name="groups"
[]
The response is:
{"groups": ["Incorrect type. Expected pk value, received unicode."]}
I guess the problem is that FormData cannot transfer raw JSON like httpie. restframework treats them differently:
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]
This custom method makes it work but I still don't like the approach. To clear I append null to the FormData:
data.append('groups', null);
And make it an empty list on the backend:
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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments