python - Django REST serializer not working with files -
for example have following in models.py
:
def upload_attachments(filename): return '/logos/%y/%m_%d/{}'.format(filename) # well, not exactly, close class client(models.model): name = models.charfield(unique=true, max_length=255) logo = models.imagefield(upload_to=upload_attachments)
serializer model way:
class clientserializer(serializers.modelserializer): class meta: model = client fields = ( 'name', 'logo' )
the view, working model:
@renderer_classes((jsonrenderer,)) @parser_classes((formparser, multipartparser)) class clientview(apiview): def post(self, request, domain=none): data = request.data.get('data', none) serializer = clientserializer(data=data, files=request.files.get('file', none)) if serializer.is_valid(): serializer.save() return response(utils.ok, status=status.http_201_created) return response({'error': serializer.errors}, status=status.http_400_bad_request)
i send form post key file
containing logo.png
file , key data
containing json. either no arguement files
although there many examples on net of working , if leave out file (although should it) - error data
being unicode, not dict , if wrap data
json.loads()
- there "too many values unpack".
update: found problem data. easy actually:
data = request.data.get('data', none) data = data.get('data', none) # roughly, sure prettyfied serializer = clientserializer(data=data, files=request.files.get('file', none))
the problem file still stands.
well, 'ol debug helped find problem code. here final variant:
data = json.loads(request.data.get('data', none)) data = data.get('data', none) data['logo']=request.files.get('file', none) serializer = clientserializer(data=data) if serializer.is_valid(): serializer.save() return response(utils.ok, status=status.http_201_created)
this still bit clumsy, working chunk of code.
Comments
Post a Comment