Fabi0_Z
Fabi0_Z

Reputation: 195

Wrong path for ImageField in Django

I have a model with a ImageField and a function to change the upload path

class Images(models.Model):
    def upload_path(self, filename):
        return os.path.join(settings.TOOLS_IMAGE_UPLOADS, self.get_artworkID(),
                            filename)

    image = models.ImageField(upload_to=upload_path)
    artworkID = models.IntegerField(null=True, blank=True)

    def __str__(self):
        if self.title == "" or not self.title:
            return str(self.image)
        return self.title

    def get_artworkID(self):
        if self.artworkID:
            return str(self.artworkID)
        return 'temp'

The value of TOOLS_IMAGE_UPLOADS is

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_DIR)
MEDIA_NAME_FOLDER = 'media'
MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_NAME_FOLDER)
TOOLS_IMAGE_UPLOADS = os.path.join(MEDIA_ROOT, 'uploads', 'images')

The problem is that the URL returned when visualizing an Image object via Django admin or rest api is wrong

Path returned: http://localhost:8000/media/webapp/artrights/media/uploads/images/temp/file.png

Real path of the file: http://localhost:8000/media/uploads/images/temp/file.png

I'm doing something wrong or I just need to make a custom function to return the right path?

Upvotes: 2

Views: 1147

Answers (1)

Will Keeling
Will Keeling

Reputation: 23004

The upload_to callable should return a path that is relative to the MEDIA_ROOT because it will be appended to it.

The problem I think is that TOOLS_IMAGE_UPLOADS already includes the MEDIA_ROOT.

So really the function should return the part of the path after the MEDIA_ROOT:

def upload_path(self, filename):
    return os.path.join('uploads', 'images', self.get_artworkID(), filename)

Upvotes: 2

Related Questions