Home > other >  How to associate newly created file model
How to associate newly created file model

Time:01-15

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.

CodePudding user response:

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
  •  Tags:  
  • Related