How to render template with image in flask? - python

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.

Related

File Structure in Django

I am learning Django and making an ecommerce website. My File Structure is as follows:
[![My project File Structure][1]][1]
Now I am uploading some pictures but could not able to access in the web.
{% load static %}
<div class="card" style="width: 18rem;">
<img src='{% static "images/aws.png" %}' class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
Go somewhere
The above example is of an part of an carousal. Please help where I am missing something. How to give link to images in my web.
[1]: https://i.stack.imgur.com/Eio3H.jpg
I solved this by updating the settings.py file. I added this line:
STATIC_DIR = os.path.join(BASE_DIR, "media/static")

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.

Trying to pass list value from python to html

I'm trying to pass list values (from 'ci' list below) into my wepage using python. The list values contain URLs for images which will go in the HTML <img src {{ listname[1] }} tag (see HTML below for more info). However, when I try the below code and render the template on my local server the img does not appear and when I inspect element the img src tag is empty.
My code is below:
Python
#app.route('/route', methods=['GET', 'POST'])
def _get_gallery():
df=pd.read_csv('C:\\username\\foldername\\excelfile.csv')
images=list(df["image"].values)
clean_images=[]
for image in images:
if "https" in str(image):
clean_images.append(image)
ci=pd.DataFrame(clean_images)
return render_template('template.html', ci=ci)
if __name__ == '__main__':
app.run(debug=True)
The HTML template has the following code to try and pull through the list values:
<div class="row">
<div class="col">
<a href="{{ ci[1] }}">
<img class="img" src="{{ ci[1] }}" alt="">
</a>
</div>
I think you don't need to convert the list to pandas DataFrame, try to comment this line and see if its work

Using flask to serve static files: flask doesn't recognize path and defaults to 404?

I'm developing a quick url shortner which also returns a svg version of a QR code for the same shortened URL. I'm using flask and python
I've created a specific route in flask to serve the file and return the file for download with send_file, the file gets created in the root directory (I'll need to fix this later eventually, but that's a different problem) and is in there, but when I click the link in the front, flask defaults to the 404.
This is the download route:
#short.route('/<qr_file>')
def download(qr_file):
return send_file(qr_file, as_attachment=True)
and here's the add_link route (creates the link, commits to db, creates the qrcode, stores it, returns short and original url to the template, along with the qr_file location for the link to download)
#short.route('/add_link', methods=['POST'])
def add_link():
original_url = request.form['original_url']
link = Link(original_url=original_url)
db.session.add(link)
db.session.commit()
qr_url = pyqrcode.create(link.short_url)
qr_file = link.short_url + '.svg'
qr_url.svg(qr_file, scale = 8)
return render_template('link_added.html',
new_link=link.short_url, original_url=link.original_url, qr_file=qr_file)
Here's the relevant in the link_added.html:
<div class="field">
<label class="label">New URL</label>
<div class="control">
<input class="input" type="text" name="original_url" value="{{ url_for('short.redirect_url_to_url', short_url=new_link, _external=True) }}">
</div>
</div>
<div class="field">
<label class="label">QR Code</label>
{{ qr_file }} <br>
<img src="{{ qr_file }}" height="90" width="106" /><br>
</div>

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