Home > Software design >  Save ImageField to different folders
Save ImageField to different folders

Time:09-05

I have two models that inherit from a Base model as following

'''

 games = [
    ('DND5E', 'Dungeons and Dragons'),
    ('TOR20', 'Tormenta20'),
    ]
    
    class BaseSheet(models.Model):
        ...
        game: str = models.CharField(default='', max_length=5, choices=games)
        ...

    class DnDMonster(BaseSheet):
        ...
        image = models.ImageField(upload_to='images/monsters/DnD5e')
        ...

    class Tor20Monster(BaseSheet):
        ...
        image = models.ImageField(upload_to='images/monsters/Tor20')
        ...

'''

The way i'm thinking it, it's more organized that way, so I can place images from different games in different folders, not one giant folder with everything in it

I am having some problems when I want my client to see everything that inherits from BaseSheet and the their images, so I want to put this ImageField in the BaseSheet. When I try to do that, it seems I can't put the images in different folder depending on the game the Monster has. Is there a way to do so? Is there a better way to do it?

CodePudding user response:

I am not sure if it will work. But if you add the image field to the base model, but you will only create new objects over your subclass model, this could probably work:

def image_upload_path(instance, filename):
    if isinstance(instance, DnDMonster):
        return 'images/monsters/DnD5e/{0}'.format(filename)
    if isinstance(instance, Tor20Monster):
        return 'images/monsters/Tor20/{0}'.format(filename)
    return 'images/monsters/somefallbackpath/{0}'.format(filename)


class BaseSheet(models.Model):
    ...
    image = models.ImageField(upload_to=image_upload_path)
    ...
  • Related