Passing variable name into {{ }} flask [duplicate] - html

This question already has an answer here:
Reference template variable within Jinja expression
(1 answer)
Closed 4 years ago.
I want to get image name from database and make it display at html file by this code
<img src="{{ url_for('static', filename='img/{{rows.infor_image}}') }}" style="width:50%; height:60%;">
but I dont know how to write in the correct syntax to get image to be display
I try to declare image_name in .py file but I dont know how to use it
#app.route('/herbsinfo/<id>')
def landing_page(id):
cur = mysql.connection.cursor()
#Query
cur.execute('SELECT version()')
result = cur.execute("SELECT * FROM information where infor_id = %s",[id])
rows = cur.fetchone()
image_name = rows['infor_image']
if result > 0:
return render_template('herbsinfo.html', rows=rows,image_name=image_name)
or I can display image in other way

Try this :
<img src="{{ url_for('static', filename='img/'+image_name) }}" style="width:50%; height:60%;">
or
<img src="{{ url_for('static', filename='img/'+rows.infor_image) }}" style="width:50%; height:60%;">
You don't need to add extra {{ }}

Related

Image not showing up in the browser

Here's what Im trying to do.. The images I save on the database are going to the correct path. But they don't show up in the site.
#blogs.route("/post/new", methods=['GET', 'POST'])
def new_post():
if ('user' in session and session['user'] == params["username"]):
form = PostForm()
if form.validate_on_submit():
pic = save_picture(request.files['pic'])
post = Post(title=form.title.data,
content=form.content.data, img=pic)
db.session.add(post)
db.session.commit()
flash('Your post has been created!', 'success')
image_file = url_for('static', filename = 'profile_pics/' + pic)
return render_template('post.html',image_file=image_file)
return render_template('create_post.html', title='New Post',
form=form)
return "please login to the dashboard first. Dont try to enter without logging in!"
The HTML side
<img src="{{image_file}}" alt="error">
Found a fix!!
I figured out that one can use the set keyword from python as a variable to store the post.img in it and then refer it inside the source.
{% set img_name = 'profile_pics/' + post.img %}
<img src="{{url_for('static', filename = img_name)}}" alt="error">
This would be the route function:
image_file = url_for('static', filename='profile_pics/' + post.img)
return render_template('template.html', image_file=image_file)
and this is what it looks like in the template:
<img src="{{ image_file }}">
The issue is probably that You are not really able to have nested variables inside html especially because jinja probably interpreted that as a literal string

How to change image path dynamically with Flask

Hi is there a way to dynamically load different images whenever I get into my flask app?
I've got 10 images each is named 'accueil_X' with X is 0,1,2,...
app.py
#app.route('/', methods=("POST", "GET"))
def home():
random = randrange(10)
random_pix = 'accueil_'+str(random)+'.png'
HTML
<img src="{{url_for('static', filename='+{{ random_pix }}+')}}" width=100%, alt="">
Jinja seems to load an image named +{{ random_pix }}+: How can I fix this ? thank you
so you want to load a random image with each refresh of the home page:
#app.route('/', methods=("POST", "GET"))
def home():
random = randrange(10)
random_pix = 'accueil_'+str(random)+'.png'
[..]
# i added this missing line to get code more clear
return render_template('home.html', random_pix=random_pix)
Jinja seems to load an image named +{{ random_pix }}+: How can I fix this ?
it's simple, just remove the {{ }} surrounding the variable random_pix
<img src="{{ url_for('static', filename='\'' + random_pix + '\'') }}" width=100%, alt="">
jinja2 uses {{ .. }} to evaluate any valid expression
refer to this doc
You could do this with a context processor which is the equivelant of Django's "template tag".
This can be used to pass a number of variables to all templates, or pass a function which can then be called in all templates.
First import the required modules, and initialise the app:
from flask import Flask, url_for, render_template
from random import randrange
app = Flask(__name__)
Then define a context processor:
#app.context_processor
def utility_processor():
def random_image():
number = randrange(10)
f = 'accueil_' + str(number) + '.png'
return url_for('static', filename=f)
return dict(rand_im=random_image)
Notice you've passed the random_image function which can then be called in the template as rand_im. Instead of putting the call to url_for in the template, you've done this in Python.
So you could render this with the following in any template:
<img src="{{ rand_im() }}" width="100%" />

Using django custom template tag to display photos

I have pictures of objects in my static files that I would like to display. However for some objects I don't have a picture and for those I would like to display an image saying "no pic available". I therefore have a field called pictures which is set to 1 for the object with a picture available and 0 for those with no picture available.
I have made a template tag that should be able to insert the correct picture but I'm facing a problem.
template tag file:
def static_picture(id_internal, picture):
if picture == 1:
return '"' + "{% static" + ' "' + 'img/pictures/' + id_internal + '.jpg' + '"' + ' %}' + '"'
else:
return '"' + "{% static" + ' "' + 'img/pictures/picture_missing.jpg' + '"' + " %}" + '"'
html:
<img src="{{ object.id_internal|static_picture:object.picture }}" class="img-responsive">
It outputs this but shows no picture:
<img src="{% static "img/pictures/339-10026.jpg" %}" class="img-responsive">
The path is correct and the picture exists. What am I doing wrong?
It does not work like that, after the {{}} are evaluated, there is no more evaluation. So you see string.
You need to edit do code,
The Jinja (template translator create from {{}} html code) evaluate your template function and insert it to the place. After that django send this to browser:
<img src="{% static "img/pictures/339-10026.jpg" %}" class="img-responsive">
but browser does not understand this. So you have to return in your function full_path.
{% static ... %} just prefix your path with path to static folder. This path is available in settings. Settings are accessible in module settings in django.conf.
from django.conf import settings
def static_picture(id_internal, picture):
if picture == 1:
return '"{}/img/pictures/{}.jpg"'.format(settings.STATIC_URL, id_internal)
else:
return '"{}/img/pictures/picture_missing.jpg"'.format(settings.STATIC_URL)
This return full path to file
<img src="{{ object.id_internal|static_picture:object.picture }}" class="img-responsive">
<img src="path/to/static_folder/img/picturesXXX.jpg" class="img-responsive">

Django Show Image in HTML

I am new to Django and want to show an image in HTML which is identified by an item's link being clicked in a table. The ID is given when a link is clicked. HTML:
<div id="link-product">
<a id= "product-clicked" href="/prod_details/{item.id }}"> {{ item.product }}
</a>
</div>
VIEWS:
def list_details(request,info_id):
active_user = request.user
product_image = Item_Model.objects.values_list('image').filter(id=info_id)
return render(request,'prod_details.html', {'active_user': active_user, 'product_image': product_image})
Then it will go to the next page and the HTML should receive that item's ID and display its image accordingly. HTML:
<div id="info-box-container">
<img id= "product-image" src = "{{ MEDIA_URL }}{{ product_image }}" />
</div>
But when I do this, the image does not show. I am definitely missing some process. How can I get this to work as desired?
values_list returns a list of tuples but not the single value. Change your query to:
product_image = Item_Model.objects.filter(id=info_id) \
.values_list('image', flat=True).first()

Replacing image with CSS on Django if/else statement

I am trying to create a voting system similar to that of stackoverflow, but I can't figure out how to call on the css instead of the images.
I have the following code:
<input type="image" id="uparrow{{ vote.id }}" src="{{ MEDIA_URL }}static/img/aup{% if vote and vote.is_upvote %}mod{% else %}grey{% endif %}.PNG">
How can I change the code so it calls a css class instead of an img src?
You are looking for something like:
<input type="image" id="uparrow{{ vote.id }}"
src="{{ MEDIA_URL }}static/img/vote.png"
class="otherclass {% if vote and vote.is_upvote %}upvote{% else %}novote{% endif %}" />
The image would have classes "otherclass" and "upvote" in one case, "otherclass" and "novote" in the other.