Reputation: 23
I created a User class as such:
class User(UserMixin, db.Model):
###
avatar = db.Column(db.String(64), default='app/static/upload/default.jpeg')
and a user uploads his avatar as following(UPLOAD_DIR is app/static/upload):
###
img_name = secure_filename(img.filename)
img_path = os.path.join(current_app.config['UPLOAD_DIR'], \
img_name)
img.save(img_path)
current_user.avatar = os.path.join(
current_app.config['UPLOAD_DIR'],
form.avatar.data.filename)
db.session.add(current_user)
flash('Upload completed.')
Then I checked the 'uploads' dir and confirmed the img was there; and I got this in shell:
>>> z.avatar
u'C:\\Users\Administrator\\Desktop\\weiboLITE\\app/static/uploads\\162421.jpg'
Now I ran the server and found the img can't be displayed somehow. My template is like this:
<div class="thumbnail">
<img src="{{ user.avatar }}" alt="Avatar not found.">
</div>
So I wonder in which format should img be in Jinja2 templates...? Or am I wrong else where? Please kindly advise.
Upvotes: 1
Views: 609
Reputation: 109
Can you provide some additional information? What is the code for the route you use to render the jinja2 template?
Also, it looks like you haven't committed the new path to the database --- you should call db.session.commit()
after the new avatar path is added to the user object to ensure that the new data is properly saved:
current_user.avatar = os.path.join(
current_app.config['UPLOAD_DIR'],
form.avatar.data.filename)
db.session.add(current_user)
db.session.commit() # Try adding this line
flash('Upload completed.')
This matters if, say, you're sending a new user object to the jinja2 template. While the route might appear to be saved correctly when you're working with a single user object in the interactive shell, it won't be correct when you perform a new User.query
in your route and send the query object as context to the template using render_template()
.
Finally, you should be calling the image location with url_for()
. Check this other post for guidance.
Good luck -- I hope this helps!
Upvotes: 2