0

I have the following code which generates the correct filepath for the images I have, it also populates them correctly inside the generated HTML in browser, but my browser refuses to load saying, that it is 'Not allowed to load local resource'.

This is the code I have: Python3:

@app.route("/", methods=["GET", "POST"])
def main():
    conn = sqlite3.connect('mydb.db')
    c = conn.cursor()
    
    #Defines what to do when the request is GET
    if request.method == 'GET':
        allPosts = c.execute('SELECT * FROM posts ORDER BY time DESC')
        return render_template('index.html', allPosts = allPosts)

    #Defines what to do when the request is POST
    if request.method == 'POST':
        pass

@app.route("/upload", methods=["GET", "POST"])
def upload():
    conn = sqlite3.connect('mydb.db')
    c = conn.cursor()
    #Define what to do if method is GET
    if request.method == 'GET':
        return render_template('upload.html')
#Define what to do if method is POST
    if request.method == 'POST':
        #Get the data from the form
        #image = request.files['image']
        username = request.form['username']
        title = request.form['nadpis']
        post = request.form['prispevok']
        
        #Get a random ID of post
        randomIdOfPost = random.randrange(99999999)
        
        #Get current timestamp
        actualTime = datetime.now()
        actualTimeForInsertingIntoDB = str(actualTime.day) + '.' + str(actualTime.month) + '.' + str(actualTime.year) + ' ' + str(actualTime.hour) + ':' + str(actualTime.minute) + ':' + str(actualTime.second)
        
        if 'image' not in request.files:
            flash('No image part')
            return redirect('/upload', code=302)
        image = request.files['image']
        # if user does not select file, browser also
        # submit an empty part without filename
        if image.filename == '':
            flash('No selected image')
            return redirect('/upload', code=302)
        if image and allowed_file(image.filename):
            filename = secure_filename(image.filename)
            filename = str(randomIdOfPost) + '_' + filename
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            imageName = str(filename)
        
        
        #Save the post into DB
        data = [(randomIdOfPost, actualTimeForInsertingIntoDB, username, title, post, imageName)]
        c.executemany('INSERT INTO posts VALUES (?,?,?,?,?,?)', data)
        conn.commit()
      
        return redirect('/', code=302)

HTML:

{% for row in allPosts %}
    <div class="container-fluid" align="center">
    <span class="badge badge-info">#{{ row[0] }} / Pridané dňa {{ row[1] }}<br>používateľom {{ row[2] }}</span>
    <h6>{{ row[3] }}</h6>
    <p>{{ row[4] }}</p>
    <img src="{{ url_for('static', filename='{{ row[5] }}') }}" alt="my text">
</div>
<p>&nbsp;</p>   
{% endfor %}

On top of my Python3 code I also have:

UPLOAD_FOLDER = os.getcwd() + r'\static'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__, template_folder=os.getcwd(), static_folder=os.getcwd() + r'\static')
#Set the route to the static folder (folder containing css stylesheet)
app._static_folder = os. getcwd() + "\\css"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

The only issue I have is, that my browser does not allow me to show the images that someone uploaded.

All the help is much appreciated.

EDIT 1:

{% for row in allPosts %}
    <div class="container-fluid" align="center">
    <span class="badge badge-info">#{{ row[0] }} / Pridané dňa {{ row[1] }}<br>používateľom {{ row[2] }}</span>
    <h6>{{ row[3] }}</h6>
    <p>{{ row[4] }}</p>
    
    <!-- I tried both <img> tags below, none of them works.. -->
    <img src="{{ row[5] }}" alt="my text">
    <!-- <img src="{{ url_for('static', filename='{{ row[5] }}') }}" alt="my text"> -->
</div>
<p>&nbsp;</p>   
{% endfor %}
10
  • Please post the complete error message, incl line numbers Commented Jul 20, 2020 at 17:22
  • Flask does not give any errors, it's only in console of my browser that I am able to see that it says: Not allowed to load local resource. Then, where my <img> tags are, only a 'broken image' is visible...
    – rogaloo
    Commented Jul 20, 2020 at 17:24
  • Please show me the HTML source code. Especially the part where the img tags get rendered. Please put this above in the question, properly formatted as code Commented Jul 20, 2020 at 17:35
  • @J.G. I have added the HTML code where the images get populated using Jinja2. It's under the EDIT 1 in my question above. Thank you
    – rogaloo
    Commented Jul 20, 2020 at 17:43
  • Suggestion: Since it looks like you're on Windows, don't use ` with file paths in your code. Use os.path.join` et al. exclusively. And you probably don't want to be doing app._static_folder = os. getcwd() + "\\css" Commented Jul 20, 2020 at 18:13

2 Answers 2

1

This:

<img src="{{ url_for('static', filename='{{ row[5] }}') }}" alt="my text">

Should probably be:

<img src="{{ url_for('static', filename=row[5]) }}" alt="my text">
1
  • This worked out. I actually changed it to: <img src="{{ url_for('static', filename='images/'+row[5]) }}" alt="my text"> and it worked Thank you!
    – rogaloo
    Commented Jul 21, 2020 at 10:45
1

You really need to view the source code in the browser, to see what img paths are rendering. Don't nest curly braces. Try this to see if it's a path issue:

<img src="/path/to/static/{{ row[5] }}" alt="my text">

You want to unnest the vars, like:

{{ url_for('static', filename=row[5]) }}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.