I have a form that contains several text fields and one file field:
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')
What I am trying to have is a view for editing images that may or may not accept a new image. If there is a file in request.files I want to use it and replace the old image. However if there is not a file, I want the view to just update the metadata (the name, the gallery, the imagekind link etc) whilst leaving the old imagefile.
The view looks like this:
@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)
When the form is given a file/picture, everything works as it should. However, when I try without an image or file in the form, I get a 400 Bad request? Any ideas? All of the fields have the proper ids and names...