我有一个包含几个文本字段和一个文件字段的表单:
class PictureForm(Form):
title = StringField(u'Title',validators=[Required()])
description = TextAreaField(u'Description')
gallery = QuerySelectField(u'Which
gallery?',query_factory=all_galleries,validators=[Required()])
imagekind = StringField(u'Imagekind URL')
pic = FileField('Image upload')
submit = SubmitField(u'Upload/edit picture')
我想要的是一个用于编辑可能会或可能不会接受新图像的图像的视图。如果request.files中有一个文件,我想使用它并替换旧图像。但是,如果没有文件,我希望视图仅更新元数据(名称,画廊,imagekind链接等),同时保留旧的imagefile。
视图如下:
@main.route('/picture/edit/<id>', methods = ['GET', 'POST'])
@login_required
def edit_picture(id):
# old picture
picture = Picture.query.get_or_404(id)
# form data - old picture
form = PictureForm(obj=picture)
if form.validate_on_submit():
# update picture data
picture.title = form.title.data
picture.description = form.description.data
picture.gallery = form.gallery.data
picture.imagekind = form.imagekind.data
# new image if uploaded
image = request.files['pic']
filename = ''
if image:
# replace old file on disk with new image...
# some PIL processing
# new file names
else:
msg = u'No new image, just updated the metadata'
flash(msg,'warning')
db.session.add(picture)
db.session.commit()
return redirect(url_for('main.admin_page'))
return render_template('main/new_picture.html', form = form, edit=True,
picture = picture)
为表单提供文件/图片后,一切都会正常进行。但是,当我尝试不使用表格中的图像或文件时,是否收到400错误的请求?有任何想法吗?所有字段均具有正确的ID和名称...
答案 0 :(得分:0)
愚蠢的错误:我必须检查:
if 'pic' in request.files:
然后从那里拿走。