Last active
November 13, 2017 19:51
-
-
Save msukmanowsky/8086892 to your computer and use it in GitHub Desktop.
An ImageFieldRequired validator for a Flask WTForm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()]) |
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
global name 'validators' is not defined
Error i kept getting, so i used ValidationError instead, it requires importing from wtforms.validators