Search code examples
pythonhtmlflaskjinja2

how can i display mysql content using 2 for loops is flask jinja2


I have written a code in flask in which users are allowed to upload images and along with image they can ask questions for taking user questions i have created a form and on submitting form user questions are stored into the database I am able to retrieve the question from database and images and diplay them in HTML using jinja2 What I want is to display the image and below that display its comment

from flask import Flask,request,render_template,redirect,url_for,session,logging,flash,send_from_directory
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
from flask_mail import Mail
app = Flask(__name__)
import os

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/akashauto'
db = SQLAlchemy(app)    
class Upload_tb(db.Model):
    snob = db.Column(db.Integer, primary_key=True)
    commentb = db.Column(db.String(20), unique=True, nullable=False)
    datab = db.Column(db.String(20), unique=True, nullable=False)

APP_ROOT=os.path.dirname(os.path.abspath(__file__))
@app.route("/plcpro")
def problem():
    return  render_template("plcpro.html")




@app.route("/uploader",methods=["GET","POST"])
def uploader():
    target=os.path.join(APP_ROOT,"images/")
    print(target)
    if not os.path.isdir(target):  #if folder does not exist . create a folder
        os.mkdir(target)
    if(request.method=='POST'):
        f=request.files['file1']
        text=request.form.get('comment')
        filename=f.filename
        f.save(os.path.join(target,filename))
        image=os.listdir('./images')
        existing_entry=Upload_tb.query.filter_by(commentb=text).first()
        if existing_entry:
            # flash('Email already exist','danger')
            return redirect(url_for("plcove"))
        new_entry=Upload_tb(commentb=text,datab=filename)
        db.session.add(new_entry)
        db.session.commit()
        question=Upload_tb.query.all()
    return render_template('ans.html',file=filename,text=text,image=image,question=question)
@app.route("/uploader/<filename>")
def send_img(filename):
    return send_from_directory("images",filename)

This is the Form code

      <form id="upload-form" action="/uploader" method="POST" enctype="multipart/form-data" onsubmit=" return askvalidateform()">
        <div class="form-group">
            <label for="name">Enter Name:</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="Enter your name">
            <span id="nameerror" class="text-danger"></span>
          </div>

          <div class="form-group">
            <label for="comment">Ask Your Question: </label>
            <textarea rows="5" cols="30" class="form-control " id="comment" name="comment"
              placeholder="Ask Question"></textarea>
            <span id="commenterror" class="text-danger"></span>
          </div>
        <input type="file" name="file1" accept="image/" multiple>
        <input type="submit" value="send">
        </form>

display code

  {% for image_name in image %}
             <li class="list"><img src="{{url_for('send_img',filename=image_name)}}"></li>
{%endfor%}
<p class="para">{% for user in question %}</p>
             <li class="list">Comment - {{user.commentb}}</li>

{% endfor %}

The output i am getting is enter image description here

1st images are displayed and then comments what i want to display is image and its comment together so can i do some changes in for loop?Any help will be appriciated


Solution

  • You could use this method. Iterate through both arrays at once, and then access the values:

    {% for i in range(images|length)%}
    <p> {{question[i].commentb }} </p>
    <img src='url_for("send_image", filename=images[i])}}'>
    {% endfor %}