Filename breaks when passed from Flask to Jinja2 [duplicate] - python

This question already has an answer here:
Reference template variable within Jinja expression
(1 answer)
Closed 2 years ago.
When I'm sending a filename as a variable from flask to jinja2 it breaks:
I'm using SQLAlchemy to store datas about projects (title, description and a picture to illustrate), and flask to send this data to a jinja2 page. This is the route:
#app.route('/projects')
def projects():
project_matrix = listOfProjects()
for i in range(0, len(project_matrix)):
print(project_matrix[i][3])
return render_template("projects.html", projects=project_matrix)
print(project_matrix[i][3]) shows in the terminal the name of the file of the picture for each project. This is what appears in the terminal when I reload the page
tethermc.jpg
graph.png
127.0.0.1 - - [13/May/2020 01:07:20] "GET /projects HTTP/1.1" 200 -
127.0.0.1 - - [13/May/2020 01:07:20] "GET /static/css/main.css HTTP/1.1" 200 -
127.0.0.1 - - [13/May/2020 01:07:20] "GET /static/img/uploads/%7B%7Bproject%5B3%5D%7D%7D HTTP/1.1" 200 -
127.0.0.1 - - [13/May/2020 01:07:20] "GET /favicon.ico HTTP/1.1" 200 -
and this is the template of the page:
{% for project in projects %}
<div class="project">
<div class="projectTitle">
{{ project[1] }}
</div>
<div class="projectHolding">
<div class="projectDescription" type="html">
{{ project[2] }}
</div>
<div class="projectImg">
<img
src="{{ url_for('static', filename = 'img/uploads/'+'{{project[3]}}') }}"
style="min-width: 100px; max-height: 300px;"
alt="alt"
/>
</div>
</div>
</div>
{% endfor %}
When I load the page, the content isn't altered except the images that don't show up. When I inspect the elements (the image block) I see:
<img
src="/static/img/uploads/%7B%7Bproject%5B3%5D%7D%7D"
style="min-width: 100px; max-height: 300px;"
alt="alt"
/>
There is src="/static/img/uploads/%7B%7Bproject%5B3%5D%7D%7D"
instead of src="/static/img/uploads/ethermc.jpg"
or src="/static/img/uploads/graph.png"
Do you have any idea of what's causing the problem ?

The problem is on this line:
src="{{ url_for('static', filename = 'img/uploads/'+'{{project[3]}}') }}".
First, there are single quotes around this part: '{{project[3]}}' which is causing those characters to be interpreted literally, rather than doing "what you wanted" and using the value in the project[3] variable. If you URL encode a curly brace, you get %7B or %7D, which might help you see how your incorrect filename was composed!
Second, you are "nesting" your curly braces, which isn't needed. The {{ }} next to project[3] are being interpreted literally as braces, which are being encoded to the %7B and %7D you are seeing in your final filenames. They are not needed here, because when you opened the "outside" curly braces, you are now in a code block, and everything in between is (basically) python code.
So the Python code you want to run is:
url_for('static', filename = 'img/uploads/'+project[3])
This means you should replace that line with:
src="{{ url_for('static', filename = 'img/uploads/'+project[3]) }}"

Related

Fail to pass/use string argument for img to html file in Django app?

I am very new to Django and was trying to pass one argument as a string to my html file so that I can call to use my image.
I have the below code to call static image:
{% load static %}
<img src= "{{ user_age_pic_name }}" width=950 height=450px padding = 40px alt="" >
However, this is not working (I also tried deleting the double quote).
I know the image is correct because when I call
<img src= "{% static 'research/used_viz/comparative/age/12-15.jpg' %}" width=950 height=450px padding = 40px alt="" >
The img works perfectly.
I also try to just print out the text and it seems to work fine. I think it should be cause by limited understanding of HTML arguments. Could someone guide me through this? Any input is appreciated!
You just need to add .url
<img src= "{{ user_age_pic_name.url }}" width=950 height=450px padding = 40px alt="" >

Flask access json data and embedding it in a <img> tag [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 1 year ago.
I have the following flask route
#app.route("/rec_demo")
def rec_demo():
print("de lokos")
response_data = {"rec_one": "pic_trulli.jpg"}
return render_template("demografico.html", data=response_data)
And I try to access the rec_one to display it as an image
<div id='info_section'>
<img src={{ data.rec_one }} alt="Girl in a jacket" width="500" height="600">
</div>
But when I check the web on a live server the src doesn't resolve to the url I passed. If instead I had
<div id='info_section'>
{{ data.rec_one }}
</div>
I can see the url value as text in my webpage
You should be putting quotes around your flask call -- IE
<img src="{{ data.rec_one }}" alt="Girl in a jacket" width="500" height="600">
This will cause problems not only with the flask output .. But the browser's interpretation as well.

Why does Python Flask throw a HTTP 404 error

It is several years since I have used Flask, starting on a new project.
I get a HTTP 404 error. The requested URL is not found??
The index and the requested URL are both in the templates folder.
I don't understand why it is throwing a HTTP 404 error??
Any pointers appreciated, thanks.
Clive
I have a code snippet in routes.py.
#app.route('/service_response', methods=['GET','POST'])
def service_response():
servicesql = "SELECT * FROM DASHBOARD_SERVICE_RESPONSE"
data = list(conn.execute(servicesql))
return render_template('service_response.html', service_response=servicesql)
In index.html I have:
<div class="form chartdisplay" >
<div class="form-heading">BCC Report Period</div>
<br>
<div class="form-group"; class="height-auto";>
<table>
<thead>
<iframe src="service_response.html" width="90%" height="90%"></iframe>
</thead>
</table>
</div>
</div>
Your code points to src="service_response.html" while what you want to do is to point to /service_response which will render the 'service_response.html' jinja template.

How to render template with image in flask?

I'm trying to render a template that uses image using flask but I'm encountering the following error:
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'static'.
I get the following error message on page:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I already tried to put the images in the same directory as app.py but the images did not appear. I am using flask 1.0.3.
gallery.html:
<body>
<h2>Images Side by Side</h2>
<div class="row">
<div class="column">
<img src="{{url_for('static', filename='resultado_final.png)}}" alt="Resultado final" style="width:100%">
</div>
<div class="column">
<img src="{{url_for('static', filename='resultado_final.png)}}" alt="Resultado final" style="width:100%">
</div>
</div>
</body>
app.py:
#app.route('/uploaded/<filename>', methods=['GET', 'POST'])
def uploaded_image(filename):
img_seg = main(filename)
return render_template("gallery.html", name=None)
File structure:
app.py
static
|----resultado_final.png
templates
|----gallery.html
As the error says, it should be
<img src="{{ url_for('static', filename='resultado_final.png') }}" alt="Resultado final" style="width:100%">
noting the ' at the end of the filename.

Variable in Flask static files routing [url_for('static', filename='')] [duplicate]

This question already has an answer here:
Reference template variable within Jinja expression
(1 answer)
Closed 6 years ago.
I'm making a simple music app.
I want to allow users upload their audio files and I have a page where I'm planning to show all songs.
I've created a template, and the structure looks like:
{% for song in songs %}
<div class="chart-item">
<div class="chart-position col-md-1">
<h3>#u</h3>
</div> <!-- chart-position -->
<div class="band-logo col-md-2">
<img src="{{ url_for('static', filename='uploads/users/{{ song['artistName'] }}/{{ song['pathToCover'] }}')}}">
</div> <!-- band-logo -->
<div class="band-name-and-autio col-md-9">
<div class="band-name">{{ song['artistName'] }} - {{ song['songName'] }}</div> <!-- band-name -->
<div class="audio">
<audio>
</audio>
</div> <!-- audio -->
</div> <!-- band-name-and-autio -->
<div class="clearfix"></div>
</div> <!-- chart-item -->
{% endfor %}
Here I want to make a dynamical path to cover image and a record, but I do not know to correctly write the path to the file here:
<img src="{{ url_for('static', filename='uploads/users/{{ song['artistName'] }}/{{ song['pathToCover'] }}')}}">
Please, explain how to do it. I've tried to find the solution on flask web page, but for now I have no any result.
I don't believe you can nest template tags like that. But you also shouldn't need to.
<img src="{{ url_for('static', filename='uploads/users/') }}{{ song['artistName'] }}/{{ song['pathToCover'] }}">
You can see why this works from the following example:
>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> with app.test_request_context():
... print url_for('static', filename='uploads/users/')
/static/uploads/users/
So then you just need to add the artistName, /, pathToCover
I think you can do
<img src="{{ url_for('static', filename='uploads/users/'+ song['artistName']+'/'+ song['pathToCover'])}}">
It works for me :)

Categories

Resources