jeudi 3 juin 2021

I am trying to show a random image from a folder in flask with jinja2 that has a boolean attribute

I am trying to create a function that will show a random image inside my bootstrap carousel that is in my folder and has a boolean attribute as an "featured" image. Currently nothing appears inside the carousel This is my Main/route:

from flask import Blueprint, render_template, redirect, url_for, request
from flask_paginate import Pagination, get_page_args
from app.models import User, Event, Category
import os
import random

main = Blueprint('main', __name__)

imgs = os.listdir('app/static/pics')
imgs = ['pics/' + file for file in imgs]

@main.route('/')
@main.route('/index', methods=['GET', 'POST'])
@main.route('/index/<cat>', methods=['GET', 'POST'])
def index(cat=None):
    page = int(request.args.get('page', 1))
    per_page = 6
    offset = (page - 1) * per_page
    featuredimage = random.sample(imgs,k=5)

    events = Event.query.order_by(Event.title.asc())
    categories = [cat.name for cat in Category.query.all()]
    if cat is not None:
                events = [b.events.order_by(Event.date.asc()) for b in Category.query.filter_by(name=cat)][0]

    events_for_render = events.limit(per_page).offset(offset)
    search =False
    q = request.args.get('q')
    if q:
        search=True
    pagination = Pagination(
        page=page, 
        per_page=per_page,
        offset=offset,
        total=events.count(),
        css_framework='bootstrap3',
        search=search
        )

    return render_template('index.html', events=events_for_render,
    pagination=pagination, categories=categories, title='Home', featuredimage=featuredimage)

This is the section on my index page:

 <div class="carousel-item active">
        
    

    </div>



Aucun commentaire:

Enregistrer un commentaire