Developer Interface

Forms and Fields

class flask_wtf.FlaskForm(*args, **kwargs)

Flask-specific subclass of WTForms Form.

If formdata is not specified, this will use flask.request.form and flask.request.files. Explicitly pass formdata=None to prevent this.

class Meta
property csrf

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

property csrf_field_name

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

get_translations(form)

Override in subclasses to provide alternate translations factory. See the i18n documentation for more.

Parameters

form – The form.

Returns

An object that provides gettext() and ngettext() methods.

wrap_formdata(form, formdata)

wrap_formdata allows doing custom wrappers of WTForms formdata.

The default implementation detects webob-style multidicts and wraps them, otherwise passes formdata back un-changed.

Parameters
  • form – The form.

  • formdata – Form data.

Returns

A form-input wrapper compatible with WTForms.

hidden_tag(*fields)

Render the form’s hidden fields in one call.

A field is considered hidden if it uses the HiddenInput widget.

If fields are given, only render the given fields that are hidden. If a string is passed, render the field with that name if it exists.

Changelog

Changed in version 0.13: No longer wraps inputs in hidden div. This is valid HTML 5.

Changed in version 0.13: Skip passed fields that aren’t hidden. Skip passed names that don’t exist.

is_submitted()

Consider the form submitted if there is an active request and the method is POST, PUT, PATCH, or DELETE.

validate_on_submit(extra_validators=None)

Call validate() only if the form is submitted. This is a shortcut for form.is_submitted() and form.validate().

class flask_wtf.Form(...)

Declarative Form base class. Extends BaseForm’s core behaviour allowing fields to be defined on Form subclasses as class attributes.

In addition, form and instance input data are taken at construction time and passed to process().

class flask_wtf.RecaptchaField(*args, **kwargs)
class flask_wtf.Recaptcha(message=None)

Validates a ReCaptcha.

class flask_wtf.RecaptchaWidget
class flask_wtf.file.FileField(*args, **kwargs)

Werkzeug-aware subclass of wtforms.fields.FileField.

class flask_wtf.file.FileAllowed(upload_set, message=None)

Validates that the uploaded file is allowed by a given list of extensions or a Flask-Uploads UploadSet.

Parameters
  • upload_set – A list of extensions or an UploadSet

  • message – error message

You can also use the synonym file_allowed.

class flask_wtf.file.FileRequired(message=None)

Validates that the data is a Werkzeug FileStorage object.

Parameters

message – error message

You can also use the synonym file_required.

CSRF Protection

class flask_wtf.csrf.CSRFProtect(app=None)

Enable CSRF protection globally for a Flask app.

app = Flask(__name__)
csrf = CSRFProtect(app)

Checks the csrf_token field sent with forms, or the X-CSRFToken header sent with JavaScript requests. Render the token in templates using {{ csrf_token() }}.

See the CSRF Protection documentation.

exempt(view)

Mark a view or blueprint to be excluded from CSRF protection.

@app.route('/some-view', methods=['POST'])
@csrf.exempt
def some_view():
    ...
bp = Blueprint(...)
csrf.exempt(bp)
class flask_wtf.csrf.CSRFError(description=None, response=None)

Raise if the client sends invalid CSRF data with the request.

Generates a 400 Bad Request response with the failure reason by default. Customize the response by registering a handler with flask.Flask.errorhandler().

Parameters
flask_wtf.csrf.generate_csrf(secret_key=None, token_key=None)

Generate a CSRF token. The token is cached for a request, so multiple calls to this function will generate the same token.

During testing, it might be useful to access the signed token in g.csrf_token and the raw token in session['csrf_token'].

Parameters
  • secret_key – Used to securely sign the token. Default is WTF_CSRF_SECRET_KEY or SECRET_KEY.

  • token_key – Key where token is stored in session for comparison. Default is WTF_CSRF_FIELD_NAME or 'csrf_token'.

flask_wtf.csrf.validate_csrf(data, secret_key=None, time_limit=None, token_key=None)

Check if the given data is a valid CSRF token. This compares the given signed token to the one stored in the session.

Parameters
  • data – The signed CSRF token to be checked.

  • secret_key – Used to securely sign the token. Default is WTF_CSRF_SECRET_KEY or SECRET_KEY.

  • time_limit – Number of seconds that the token is valid. Default is WTF_CSRF_TIME_LIMIT or 3600 seconds (60 minutes).

  • token_key – Key where token is stored in session for comparison. Default is WTF_CSRF_FIELD_NAME or 'csrf_token'.

Raises

ValidationError – Contains the reason that validation failed.

Changelog

Changed in version 0.14: Raises ValidationError with a specific error message rather than returning True or False.