Flask sqlalchemy image from db is not displaying in html

21 views Asked by At

I used flask SQLAlchemy to upload an image. after uploading the image it's stored in database but is not displaying in html browser. It seems to be okay. I don't find the solution. no error is displaying as well. In htlm browser, it's showing just a small photo icon. Nothing else.

main.py

app = Flask(__name__)
app.config["UPLOAD_PATH"] = "static/"

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
db = SQLAlchemy(model_class=Base)
db.init_app(app)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_PATH = os.path.join(APP_ROOT, 'uploads')

class Gallery(db.Model):
    __tablename__ = "gallery"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    image: Mapped[str] = mapped_column(String(500))

class GalleryForm(FlaskForm):
    image = FileField('Add Gallery Photo', validators=[FileRequired(), FileAllowed(['jpg','png'], 'Images only!')])
    submit = SubmitField("Add Gallery Photo")

@app.route('/admin', methods=["GET", "POST"])
def index():
    gallery_form = GalleryForm()
    if gallery_form.validate_on_submit():
        new_gallery = Gallery()

        # Handling file upload
        uploaded_file = gallery_form.image.data
        filename = secure_filename(uploaded_file.filename)
        image_path = os.path.join(app.config['UPLOAD_PATH'], filename)
        uploaded_file.save(image_path)
        new_gallery.image = image_path
        path_list = new_gallery.image.split('/')[1:]
        new_path = '/'.join(path_list)

        new_gallery.image = new_path

        db.session.add(new_gallery)
        db.session.commit()
        return redirect(url_for('index'))

    gallery_image = db.session.execute(db.select(Gallery)).scalars().all()
    return render_template("index.html" all_gallery=gallery_image, gallery_form=gallery_form)

index File:
{% for photo in all_gallery %} 
    <img src="{{ photo.image }}">
{% endfor %}
0

There are 0 answers