0

This is the model I am using to upload and rename image files in Django,

@deconstructible
class PathAndRename(object):
    def __init__(self, sub_path):
        self.path = sub_path

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        filename = '{}.{}'.format(uuid4().hex, ext)
        return os.path.join(self.path, filename)


class Diagram(models.Model):
    diagram = models.FileField(upload_to=PathAndRename("diagrams/"))
    text = models.CharField(max_length = 48)
    date = models.DateTimeField(auto_now_add=True, blank=True, null=True)

Now the images are saved in both .jpg and .png as per its original format.

My question is how to make all the uploads, be it .jpg file or .png file to store in common format e.g. all images in .png file.

Bidhan Majhi
  • 1,320
  • 1
  • 12
  • 25
  • I think this question will help you. [https://stackoverflow.com/questions/10759117/converting-jpg-images-to-png](https://stackoverflow.com/questions/10759117/converting-jpg-images-to-png) – joshlsullivan Oct 12 '18 at 09:24

2 Answers2

1

I guess I figured out the answer,

 def __call__(self, instance, filename):
    png = "png"
    filename = '{}.{}'.format(uuid4().hex, png)
    return os.path.join(self.path, filename)
Bidhan Majhi
  • 1,320
  • 1
  • 12
  • 25
0

I would use django signals for this, something like below:

from Pil import Image
import os
@receiver(post_save, sender=Diagram)
def image_to_png(sender, instance, **kwargs):
    if kwargs.get('created') and instance.diagram:
        filename, file_ext = os.path.splitext(instance.diagram.path)
        if file_ext != ".png":
            im = Image.open(instance.diagram.path)
            im.save(instance.diagram.path.replace(file_ext, ".png")

Just remove the created verification if you want to check on every update.

May.D
  • 1,832
  • 1
  • 18
  • 34
  • Did not work. @post_save giving error so I changed it to @receiver(post_save, sender=Diagram). But the images are in __.jpg__ after upload. – Bidhan Majhi Oct 12 '18 at 12:08
  • Are you sure the signal is triggered ? You could had a print to check it. – May.D Oct 12 '18 at 12:12
  • I have figured out the answer, with in `def __call__`. I will try your answer as well and will let you know. Thanks. – Bidhan Majhi Oct 12 '18 at 12:29