I am trying to upload an image file and to save it as base64 in PostgreSQL using Django Rest Framework. My files are as follows:
Models.py:
from django.db import models
import base64
class MyImageModel(models.Model):
image_file = models.ImageField( upload_to="photos/", max_length=6000, null = True)
def save(self, *args, **kwargs):
if self.image_file:
file = str(self.image_file)
image = open(file, 'rb')
image_read = image.read()
self.image_64_encode = base64.encodebytes(image_read)
print('This is the image in base64: ' str(self.image_64_encode))
super(MyImageModel, self).save(*args, **kwargs)
serializers.py:
from django.forms import ImageField
from drf_extra_fields.fields import Base64ImageField
from .models import *
from rest_framework import serializers
class MyImageModelSerializer(serializers.ModelSerializer):
image_file = serializers.ImageField
class Meta:
model = MyImageModel
fields = ('image_file',)
Views.py:
from .models import *
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
import base64
from imagebase64app.serializers import MyImageModelSerializer
# Create your views here.
class AddImageView(APIView):
def post(self, request, format=None):
serializer = MyImageModelSerializer(data = request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response({'message':'Registered Successfully!'},status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
CodePudding user response:
you can you Base64ImageField from drf_extra_fields.fields
in your serializer
keep your model as it is
and update your serializer to
class MyImageModelSerializer(serializers.ModelSerializer):
image_file = Base64ImageField(required=True)
class Meta:
model = MyImageModel
fields = ('image_file',)
CodePudding user response:
first you must take image value(base 64) from request.POST data, then convert this value(base 64) to image file and save that into your desired route(photos/
)and finally, just save image path in image_file
field of your model
something like this in views
user = User.objects.filter(id=1) #example
p_img = request.POST.get('image')
try:
img_name = 'your desired image name' '.png'
path = 'photos/' img_name
img_data = base64.b64decode(p_img)
with open(path, 'wb') as g:
g.write(img_data)
except Exception as e:
img_name = 'p_img'
user.update(profile_image=img_name)