Как связать вновь созданную модель файла
У меня такой код,
@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
Этот код не связывает файл с экземпляром модели. Я просмотрел django ContentFile и File. но все еще не могу разобраться с этим, так как примеры не очень полезны.
попробуйте что-то вроде этого, вы должны использовать 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