Search code examples
pythondjangodjango-cmsdjango-filer

How to select a random file from a folder that where uploaded with django-filer


I use django-cms for a project and in the frontend (template) I want to select a random image from a folder.

The media is managed by django-filer. I know how to use the files when I assign them directly in my models, but I can't figure out if and how it is possible to select a random image.

For a better understanding, I have a model where I can choose an image. If that is not set by the editor, I want to choose a random image as backup.


Solution

  • To solve this I had to use the Folder model of the filer. This is my model:

    class HeroExtension(TitleExtension):
    
        image = FilerImageField(
            blank=True,
            null=True
        )
    
        def get_hero_image(self):
            if self.image:
                return self.image
    
            folder = Folder.objects.filter(name='Heros')
            if folder:
                file = random.choice(folder.first().files)
                if file:
                    return file
    
            return None
    

    First I return the image of the model, if it is set. if not, I look for the specific folder and select a random image from that.

    If nothing is found, I return None in any other case an image will be returned.

    My template looks like this:

    {% if request.current_page.get_title_obj.heroextension.get_hero_image %}
    {% with hero_image=request.current_page.get_title_obj.heroextension.get_hero_image %}
    <img class="hero__image"
         alt="{{ hero_image.default_alt_text }}"
         srcset="{{ hero_image|thumbnail_url:'hero-450' }} 800w,
                 {{ hero_image|thumbnail_url:'hero-576' }} 1024w,
                 {{ hero_image|thumbnail_url:'hero-768' }} 1360w,
                 {{ hero_image|thumbnail_url:'hero-1080' }} 1920w"
         sizes="100vw"
         src="{{ hero_image|thumbnail_url:'hero-1080' }}">
    {% endwith %}
    {% endif %}