How to send a custom variable in a flask in Flask to JS/HTML to render an image?

Question:

Here is my basic python code to send the variable account name over to the javascript which will render the image.

@app.route('/<username>', methods=['GET', 'POST'])
def user_profile_name(username):
    # return f"welcome to profile page {username}"
    my_friends = database.GET_FRIENDS(connection, username)
    # print(send_string)
    return render_template(f"user_profile.html", friends=my_friends, account_name=username)

Here is my HTML that should go to the file with that name

<div>{{account_name}}</div>
<div id="profile picture">
    <h1>Profile Picture</h1>
    <img src="{{url_for('static', filename='#UserData/{{account_name}}/profile/profile_pic.jpg')}}"  width='200' height='200' />

The image is there, and if I put the name in manually like so, it works, any idea how I can send my name over?

filename='#UserData/MY_NAME_HERE/profile/profile_pic.jpg')}}"  width='200' height='200'

thanks for your time

Asked By: Andre

||

Answers:

  1. Sanitize the file name
  2. Concatenate your variable inside the string for the Jinja2 variable
account_name = secure_filename(account_name)
<img src="{{url_for('static', filename='#UserData/' ~ account_name ~ '/profile/profile_pic.jpg')}"  width='200' height='200' />

(Also, are you sure that you want that hashtag before UserData, and that mix of camel case and snake case? Better to use dash case for HTML. )

Answered By: Jonathan Ciapetti
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.