简体   繁体   中英

how to render images dynamically in flask by using python and jinja2 html template

I am using Flask-Python and to create a transport application that I've wanted to make for awhile. I'm having problems with a particular feature which is the standard file uploading. What I want to do is to try to dynamically render an image from my images folder based on a particular model but I seem to be having a problem trying to string interpolate.

def createuser(request):
   file = request.files['aadharimage']
   if file.filename == None:
       flash('No selected file')
       return redirect(request.url)
   filename=''
   if file:
      filename = secure_filename(file.filename)
      file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
users= Enduser(name=request.form["name"],fathername=request.form['fathername'],password=request.form["password"], aadhar_image=filename,email=request.form["email"],address=request.form["address"],type=request.form["type"],location_id=request.form["location_id"],mobile=request.form['mobile'],usertype=request.form['usertype'],lastlogin=request.form['lastlogin'],companyname=request.form['companyname'])

sqlsession.add(users)
sqlsession .commit()

@app.route ('/page/newuser')
def pagenewuser():
   if session['username']:
      return render_template("newuser.html", user session['username'],Locations=getlocation().all())
  else:
     flash('Please Login first!!')
     return main()

@app.route('/page/edituser')
def pageedituser():
   if session['username']:
      users = getusers()
   if users.first()== None:
      return render_template("empty.html", user=session['username'])
  else:
     return render_template("edituser.html",  user=session['username'], endusers=users.all() )

jinja2 template code

<td>{{Values.id}}</td>
<td>{{Values.name}}</td>
<td>{{Values.fathername}}</td>
<td><img src="{{url_for('static',filename='assets/images/{{Values.aadhar_image}}')}}" alt="sample"  width="25" height="24"/></td>

here {{Values.aadharimage}} is not working.can you solve my problem

you can use

<td>{{Values.id}}</td>
<td>{{Values.name}}</td>
<td>{{Values.fathername}}</td>
{% set fname='assets/images/'+ Values.aadhar_image %}
<td><img src="{{url_for('static',filename=fname)}}" alt="sample"  width="25" height="24"/></td>

I hope this will work fine for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM