I think this is the cleanest and shortest way to do this.
Let's say you have a model as follows:
Class MyImageModel(models.Model): image = models.ImageField(upload_to = 'geo_entity_pic') data=model.CharField()
Thus, the corresponding serializer will look like this:
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 may 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)
Note. In the Serializer, I used the Base64ImageField implementation provided in the django-extra-field module
To install this module, run the command
pip install pip install django-extra-fields
Import the same and do it!
Send (via the post method) your image as a Base64 encoded String in a JSON object along with any other data that you have.
Nikhil
source share