我使用html和flask创建了一个表单。用户将填写他的姓名,地址和其他信息,并上传他的照片和其他文件。一旦用户填写信息并提交表格,他将被重定向到另一页,页面上有他自己填写的信息和照片。
我可以填写用户信息并将其重定向到另一个页面“apply.html”,但是当我尝试上传照片时。它可以上传图片,但不会将我重定向到“apply.html”
在我的routes.py
中def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/form.html', methods=['POST'])
def upload_file():
nform = NewRegistration(request.form)
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
@app.route('/form.html', methods=['GET', 'POST'])
def form():
nform = NewRegistration(request.form)
if request.method == 'POST':
if nform.validate() == False:
flash('All fields are required.')
return render_template('form.html', form=nform)
else:
post = request.form['element_15'].strip()
name = request.form['element_1_1'].strip()
last = request.form['element_1_2'].strip()
Name = str(name)+ ' ' +str(last)
father = request.form['element_2'].strip()
mother = request.form['element_3'].strip()
gender = request.form['element_17'].strip()
data = {'Name' : Name, 'post' : post, 'father' : father}
return render_template("apply.html", data=data)
elif request.method == 'GET':
return render_template('form.html', form=nform)
我知道问题是由于两个函数“upload_file”和“form”所以建议我获取信息和照片的最佳方式,并且还能够将用户重定向到apply.html
答案 0 :(得分:1)
因为你需要在
中添加render_template()@app.route('/form.html', methods=['POST'])
def upload_file():
// do something
render_template("yourpage.html")
每条路线都必须返回响应。 另外我建议使用相同的路由来保存文件+表单。
@app.route('/form.html', methods=['GET', 'POST'])
def form():
nform = NewRegistration(request.form)
if request.method == 'POST':
if nform.validate() == False:
flash('All fields are required.')
return render_template('form.html', form=nform)
else:
try:
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
except Exception as e:
print "Form without file "+e
post = request.form['element_15'].strip()
name = request.form['element_1_1'].strip()
last = request.form['element_1_2'].strip()
Name = str(name)+ ' ' +str(last)
father = request.form['element_2'].strip()
mother = request.form['element_3'].strip()
gender = request.form['element_17'].strip()
data = {'Name' : Name, 'post' : post, 'father' : father}
return render_template("apply.html", data=data)
elif request.method == 'GET':
return render_template('form.html', form=nform)
如果有帮助,请告诉我。