Why is my Pillow Image not being considered a File when I try to save it into my django image field?

I'm writing a Form Creation/Filling out forms app, and I'm to the point where I'm taking canvas data from the front-end and filled out fields of text input and draw them on a picture of the form with the pillow library. The problem is when I try to save the data for the form I get this error from "serializer.error" from django-rest-framework: "'FilledForm': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]}"

Here is the Api view:

@api_view(['POST'])
def postForm(request):
   dataDict = request.data
   FieldCoords = {}
   # Define Formtype

   selectedForm = dataDict["SelectedForm"]
   del dataDict["SelectedForm"]

   # Get Datalist for form creation
   datalist = list(FormData.objects.filter(FormType=selectedForm).values())        

   #Set Signature Images on Form and Fill form with inputs

   for field in datalist:
    #Get Field Positions of Model
       if field["FieldType"] == "SignatureField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"])
       elif field["FieldType"] == "TextField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"],abs(field["height"]))
       elif field["FieldType"] == "DateField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"])

#print(FieldCoords)

#Place Signature Fields On FormImage

   sigFields = json.loads(dataDict["Signatures"])
   FormImage = Image.open(f"{MEDIA_ROOT}/{selectedForm}")
   del dataDict["Signatures"]
   for field in sigFields:
       datauri = sigFields[field]
       uri = datauri.split("base64,")
       sNameselect = field.split("  -  ")

       bytes = base64.b64decode(uri[1])  
       img = Image.open(io.BytesIO(bytes))

       for keyCoordSet in FieldCoords:
           print(keyCoordSet)
           print("Name" + sNameselect[0])
           if sNameselect[0] == keyCoordSet:
               print("Im here")
               FormImage.paste(img, FieldCoords[keyCoordSet], mask=img)

#Place Text Fields On FormImage
   d1 = ImageDraw.Draw(FormImage)
   for field in dataDict:
       for keyCoordSet in FieldCoords:
           if field == keyCoordSet:
               myFont = ImageFont.truetype("LiberationMono-Regular.ttf",size=FieldCoords[keyCoordSet][2] - 10)
               d1.text((FieldCoords[keyCoordSet][0]+5,FieldCoords[keyCoordSet][1]+5), dataDict[field], fill =(255, 255, 255),font=myFont)
   time = str(timezone.now()).split(" ")


   image_bytes = io.BytesIO(FormImage.tobytes())
   imageFile = ContentFile(image_bytes.getvalue())
   print(imageFile.read())
   data = {                                           # Final data structure
       "FormType": selectedForm,
       "DateCreated": time[0],
       "Data": json.dumps(dataDict, indent = 4),
       "FilledForm": (str(selectedForm),imageFile)

   }

   serializer = FilledFormdataSerializer(data=data)

   print(type(imageFile))
   if serializer.is_valid():
       print("Im Valid")
       #serializer.save()
   else:
       print(serializer.errors)

   return Response("Returned Data")

Here is the Model

class FilledForm(models.Model):
    FormType = models.CharField(max_length=100)
    DateCreated = models.DateField(default=timezone.now())
    Data = models.JSONField()
    FilledForm = models.ImageField()

Here is the serializer

class FilledFormdataSerializer(serializers.ModelSerializer):
    class Meta:
        model = FilledForm
        fields = ["FormType", "DateCreated", "Data", "FilledForm"]

    def create(self, validated_data):
        print(validated_data)
        return FilledForm.objects.create(**validated_data)

Heres the part of the Code where the issue is

#Place Text Fields On FormImage
d1 = ImageDraw.Draw(FormImage)
for field in dataDict:
    for keyCoordSet in FieldCoords:
        if field == keyCoordSet:
            myFont = ImageFont.truetype("LiberationMono-Regular.ttf",size=FieldCoords[keyCoordSet][2] - 10)
            d1.text((FieldCoords[keyCoordSet][0]+5,FieldCoords[keyCoordSet][1]+5), dataDict[field], fill =(255, 255, 255),font=myFont)
time = str(timezone.now()).split(" ")


image_bytes = io.BytesIO(FormImage.tobytes())
imageFile = ContentFile(image_bytes.getvalue())
print(imageFile.read())
data = {                                           # Final data structure
    "FormType": selectedForm,
    "DateCreated": time[0],
    "Data": json.dumps(dataDict, indent = 4),
    "FilledForm": (str(selectedForm),FormImage)

}

serializer = FilledFormdataSerializer(data=data)

print(type(imageFile))
if serializer.is_valid():
    print("Im Valid")
    #serializer.save()
else:
    print(serializer.errors)

Here's all the module imported

from rest_framework.response import Response
from rest_framework.decorators import api_view
from api.serializer import DataSerializer, FilledFormdataSerializer
from django.core.files import File
from django.utils import timezone
from backend.models import FormData
from django.core.files.base import ContentFile
import json
from PIL import Image, ImageDraw, ImageFont
import base64
import io
from FormApp.settings import BASE_DIR, MEDIA_ROOT

For some reason it's saying its not reading it as a file even though I'm converting it to bytes and rapping it in the ContentFile() object. Can I get some advice on why it's not saving to the image field?

Back to Top