Skip to content

Instantly share code, notes, and snippets.

@msukmanowsky
Last active November 13, 2017 19:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msukmanowsky/8086892 to your computer and use it in GitHub Desktop.
Save msukmanowsky/8086892 to your computer and use it in GitHub Desktop.
An ImageFieldRequired validator for a Flask WTForm.
from flask.ext.wtf import Form
from flask.ext.wtf.file import FileField
import imghdr
class ImageFileRequired(object):
"""
Validates that an uploaded file from a flask_wtf FileField is, in fact an
image. Better than checking the file extension, examines the header of
the image using Python's built in imghdr module.
"""
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
if field.data is None or imghdr.what('unused', field.data.read()) is None:
message = self.message or 'An image file is required'
raise validators.StopValidation(message)
field.data.seek(0)
class MyForm(Form):
photo = FileField('Photo', validators=[ImageFileRequired()])
@mrf345
Copy link

mrf345 commented Mar 25, 2017

global name 'validators' is not defined
Error i kept getting, so i used ValidationError instead, it requires importing from wtforms.validators

@kunoo
Copy link

kunoo commented Nov 13, 2017

Same thing here. Having fixed that, works like a charm.

Thx msukmanowsky!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment