Search code examples
pythondjangorestswaggerimagefield

Django REST Swagger how to process response POST api (function based)


I am trying to accept a image file that has been post using my Django REST function based POST API. This is based on https://github.com/m-haziq/django-rest-swagger-docs

I am getting this error screenshot (https://i.sstatic.net/JjUA5.jpg)

Object of type 'TypeError' is not JSON serializable

for doing this

face_image = request.data.get('face_image')

and whats the right step to save it to the model, would it be something like this

employee.face_image = face_image

Here is how I define the API

@api_view(['POST'])
def update_employee_image(request):
    # ----- YAML below for Swagger -----
    """
    description: This API deletes/uninstalls a device.
    parameters:
      - name: employee_id
        type: integer
        required: true
        location: form
      - name: face_image
        type: file
        required: true
        location: form
    """
    employee_id = request.POST.get('employee_id')
    face_image = request.data.get('face_image') <--- this causes the error

Here is the model with the imagefield

class Employee(models.Model):
    ....
    face_image = models.ImageField(upload_to='face_image/', blank=True)

Can someone let me know the right way to do this ? process the image from the post and save it to the model. My full source code is in the those links. Thanks.


Solution

  • FileUploadParser solves this issue and able to accept the image post

    parser_classes = (FileUploadParser,)
    face_image_obj = request.data['face_image']