Saving a decoded temporary image to Django Imagefield

前端 未结 3 1855
天命终不由人
天命终不由人 2020-12-28 11:03

I\'m trying to save images which have been passed to me as Base64 encoded text into a Django Imagefield.

But it seems to not be saving correctly. The database repor

3条回答
  •  没有蜡笔的小新
    2020-12-28 11:25

    I guess this is the cleanest and shortest way to do this.

    Here is how you can handle a Base64 encoded image file in a post request at the Django-based (drf also) API end which saves it as an ImageField.

    Let say you have a Model as follows:

    Class MyImageModel(models.Model):
          image = models.ImageField(upload_to = 'geo_entity_pic')
          data=model.CharField()
    

    So the Corresponding Serializer would be as follows:

     from drf_extra_fields.fields import Base64ImageField
    
     Class MyImageModelSerializer(serializers.ModelSerializers):
          image=Base64ImageField()
          class meta:
             model=MyImageModel
             fields= ('data','image')
          def create(self, validated_data):
            image=validated_data.pop('image')
            data=validated_data.pop('data')
           return MyImageModel.objects.create(data=data,image=image)
    

    The corresponding View can be as follows:

    elif request.method == 'POST':
        serializer = MyImageModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
    

    Notice In the Serializer I have used Implementation of Base64ImageField provided in the module django-extra-field

    To install this module run the command

    pip install pip install django-extra-fields
    

    Import the same and Done!

    Send (via post method) your image as an Base64 encoded String in JSON object along with any other data you have.

提交回复
热议问题