I am new here and a beginner so i would be grateful for your help.I am trying to do Blog app in Flask. I got stuck on uploading profile picture. Default picture is working fine but when i try to upload new image it just won't work. It doesn't show any error. It seems to me that maybe there is problem with storing files but i couldn't figure out what is the problem. When I try to upload an image, the page just refreshes and the default image remains. Nothing is also saved in the profile_pictures folder. Here is my layout:
/Users/korisnik/PycharmProjects/Blog
├── project
├── ├──core
| ├──posts
| ├──static
| | ├──profile_pictures
| | ├──default_profile_picture.jpg
| ├──templates
| ├──users
| | ├──__init__.py
| | ├──forms.py
| | ├──picture_handler.py
| | ├──views.py
| ├──__init__.py
| ├──models.py
├──app.py
Here is my code:
picture_handler.py
def add_profile_picture(pic_upload, username):
filename = pic_upload.filename
extension_type = filename.split(".")[-1]
storage = str(username) + "." + extension_type
filepath = os.path.join(current_app.rooth_path, "static/profile_pictures", storage)
picture_size = (100, 100)
pic = Image.open(pic_upload)
pic.thumbnail(picture_size)
pic.save(filepath)
return storage
users.views.py
@users.route("/profile", methods=["GET", "POST"])
@login_required
def profile():
form = ProfileForm()
if form.validate_on_submit():
if form.picture.data:
username = current_user.username
pic = add_profile_picture(form.picture.data, username)
current_user.profile_image = pic
current_user.username = form.username.data
db.session.commit()
return redirect(url_for("users.profile"))
elif request.method == "GET":
form.username.data = current_user.username
profile_image = url_for("static", filename="profile_pictures/" + current_user.profile_image)
return render_template("profile.html", profile_image=profile_image, form=form)
profile.html
{% extends "base.html"%}
{% block content %}
<div class="jumbotron">
<div align="center">
<h1>Welcome {{current_user.username}}</h1>
<img src="{{url_for('static', filename='profile_pictures/' + current_user.profile_image)}}" align="center">
</div>
</div>
<div class="container">
<form method="POST" action="" enctype="multipart/form-data">
{{form.hidden_tag()}}
<div class="form-group">
{{form.username.label(class="form-group")}}{{form.username(class="form-control")}}<br>
</div>
<div class="form-group">
{{form.picture.label(class="form-group")}}{{form.picture(class="form-control")}}<br>
</div>
<div class="form-group">
{{form.submit(class="btn btn-primary")}}
</div>
</form>
</div>
{% endblock %}