我正在尝试flask nad,有一个简单的任务可以提交表单。页面显示一张图片和一张表单,如果正确提交了表单,则应该更改图片,否则请更改-相同。我无法理解在表单提交后如何仅在页面上显示一个对象并获得另一个对象的机制。试图在图像列表上使用迭代器的是文件夹“静态”,但是我的实现无法正常工作。请提供给我一个反馈,以严格的方式做到这一点?
现在,我有一个简单的视图:
@app.route("/", methods=["GET", "POST"])
def start_view():
picture = None
form = InputForm(csrf_enabled=False)
if form.validate_on_submit():
picture = form.picture.data
form.picture.data = ""
return render_template('04-2.html', form=form, picture=picture)
class InputForm(Form):
picture = StringField('What is on a picture?', validators[DataRequired()])
submit = SubmitField('Submit')
和一个简单的模板:
<body>
<form method="POST">
{{ form.picture.label }} {{ form.picture }}
{{ form.submit() }}
</form>
{% if form.errors %}
<span style="color: red">{{ form.error }}</span>
{% endif %}
</body>
谢谢!
您的表格不包含任何图片。它有一个StringField
和一个SubmitField
。如果要查看任何图像,则需要<img>
在HTML中有一个标记,指向服务器中图像的位置,视图应如下所示:
from Flask import session
# in order to use sessions you have to use a secret key for your app
app.secret_key = 'some secret key'
@app.route("/", methods=["GET", "POST"])
def start_view():
img_list = ['filename1', 'filename2', 'filename3']
# if this is not the first form submission
if session.has_key('current'):
# if we reach the end of the list show the first image again
if int(session['current']) == len(img_list) - 1:
session['current'] = 0
# move to next image
else:
session['current'] = int(session['current']) + 1
else:
session['current'] = 0
picture = 'first_image_filename' # this should be the img on load
form = InputForm(csrf_enabled=False)
if form.validate_on_submit():
picture = img_list[int(session['current'])] # the filename of the next image
form.picture.data = ""
return render_template('04-2.html', form=form, picture=picture)
因此模板应如下所示:
<body>
<form method="POST">
{{ form.picture.label }} {{ form.picture }}
<img src="{{url_for('static', filename='img/' + picture)}}"
{{ form.submit() }}
</form>
{% if form.errors %}
<span style="color: red">{{ form.error }}</span>
{% endif %}
</body>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句