0

I have this code,

@receiver(post_save, sender=FileAnswer)
def save_category_signals(sender, instance, **kwargs):    
    file_types =  ["image", "image-multiple"]
    file_type = instance.question.form_input_type
    if file_type in file_types:
        image_path = instance.body.path
        image = Image.open(image_path)
        img = image.convert('RGB')
        new_path = image_path.rsplit('.', 1)
        pdf = img.save(f'{new_path[0]}_{instance.id}.pdf', format="PDF")
        # os.remove(image_path)
        
        instance.body = pdf
        instance.save()
    
    # os.remove(image_path) # remove old image

This code does not associate the file to the model instance. I have looked at django ContentFile and File. still can't really wrap my head around it as the examples aren't that helpful.

Martins
  • 1,130
  • 10
  • 26

1 Answers1

0

try something like this you should use InMemoryUploadedFile:

@receiver(post_save, sender=FileAnswer)
def save_category_signals(sender, instance, **kwargs):    
    file_types =  ["image", "image-multiple"]
    file_type = instance.question.form_input_type
    if file_type in file_types:
        image_path = instance.body.path
        new_path = image_path.rsplit('.', 1)
        image = Image.open(image_path)
        image = image.convert('RGB')
        output = io.BytesIO()
        image.save(output, format='PDF')
        output.seek(0)
        pdf = InMemoryUploadedFile(output, 'FileField',
                                   f'{new_path[0]}_{instance.id}.pdf',
                                    'application/pdf',
                                    sys.getsizeof(output), None)
        # os.remove(image_path)
        
        instance.body = pdf
        instance.save()
    
    # os.remove(image_path) # remove old image
  • Hello, this works. But I get an error `PIL.UnidentifiedImageError: cannot identify image file` – Martins Jan 14 '22 at 21:20
  • On which line exactly? – gianpiero papappicco Jan 14 '22 at 21:31
  • Could you post the entire code? – gianpiero papappicco Jan 14 '22 at 21:32
  • ` File "/home/tomms/Work/web-app/survey/signals.py", line 22, in save_category_signals image = Image.open(image_path) File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/PIL/Image.py", line 3008, in open raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file '/home/tomms/Work/web-app/media/answer/files/Screenshot_from_2021-02-14_17-41-39_66.pdf'` – Martins Jan 14 '22 at 21:46
  • `image = Image.open(image_path)` probably this line. – Martins Jan 14 '22 at 21:47
  • you are trying to open "Screenshot_from_2021-02-14_17-41-39_66.pdf" which is a pdf using Pillow, which can't read pdf. If you want to read a pdf using Pillow you must convert it to an image and then read it. – gianpiero papappicco Jan 15 '22 at 09:10