报错如下图所示:
确定forms.py表单的url和logo选择了FileField字段:
views.py 视图函数也导入了
from werkzeug.utils import secure_filename # 如下图所示
下图展示具体代码:
# 电影编辑 @admin.route('/movie/edit/<int:id>', methods=["GET", "POST"]) @admin_login_req def movie_edit(id=None): form = MovieForm() form.url.validators = [] # 因为可以不做更改,所以不需要校验 form.logo.validators = [] movie = Movie.query.get_or_404(id) if request.method == "GET": form.info.data = movie.info form.star.data = movie.star form.tag_id.data = movie.tag_id if form.validate_on_submit(): data = form.data movie_count = Movie.query.filter_by(title=data["title"]).count() if movie_count == 1 and movie.title != data['title']: flash("片名已经存在!", "error") return redirect(url_for("admin.movie_edit", id=id)) if not os.path.exists(app.config['UP_DIR']): # 存放目录不存在则创建 os.makedirs(app.config['UP_DIR']) os.chmod(app.config['UP_DIR'], "rw") if form.url.data.filename != '': old_url = movie.url file_url = secure_filename(form.url.data.filename) # 获取并转化为安全的电影文件名 movie.url = change_filename(file_url) # 调用函数生成新的文件名 form.url.data.save(app.config['UP_DIR'] + movie.url) # 保存上传的数据 if os.path.exists(app.config['UP_DIR'] + old_url): # 删除旧文件 os.remove(app.config['UP_DIR'] + old_url) if form.logo.data.filename != '': old_logo = movie.logo file_logo = secure_filename(form.logo.data.filename) movie.logo = change_filename(file_logo) form.logo.data.save(app.config['UP_DIR'] + movie.logo) if os.path.exists(app.config['UP_DIR'] + old_logo): os.remove(app.config['UP_DIR'] + old_logo) movie.title = data["title"] movie.info = data["info"] movie.star = int(data["star"]) movie.tag_id = int(data["tag_id"]) movie.area = data["area"] movie.release_time = data["release_time"] movie.length = data["length"] db.session.add(movie) db.session.commit() flash("添加电影成功", "successfully") return redirect(url_for("admin.movie_list", id=movie.id)) return render_template("admin/movie_edit.html", form=form, movie=movie)
movie_edit.html 页面的form表单:的确填写了 enctype="multipart/form-data"
<form role="form" method="post" enctype="multipart/form-data"> {{ form.csrf_token }} ...
望老师百忙之中能够抽出时间为学生解答,O(∩_∩)O谢谢
# 这个bug已经把我弄疯了