How to override the html default “Please fill out this field” when validation fails in Flask?

偶尔善良 提交于 2019-12-04 07:23:47

As of WTForms 2.2, the HTML required attribute is rendered when the field has a validator that sets the "required" flag. This allows the client to perform some basic validations, saving a round-trip to the server.

You should leave it to the browser to handle this. The messages are standard and adjusted for the user's computer's locale. There is a JavaScript API to control these messages (see Stack Overflow and MDN), although WTForms doesn't provide any integration with it (yet, a good idea for an extension).

If you really want to disable this, you can pass required=False while rendering a field.

{{ form.name(required=False) }}

You can disable it for a whole form instead by overriding Meta.render_field.

class NoRequiredForm(Form):
    class Meta:
        def render_field(self, field, render_kw):
            render_kw.setdefault('required', False)
            return super().render_field(field, render_kw)

You can disable it for multiple forms by inheriting from a base form that disables it.

class UserForm(NoRequiredForm):
    ...

You can also disable client validation without changing as much code by setting the novalidate attribute on the HTML form tag.

<form novalidate>

</form>

See the discussion on the pull request adding this behavior.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!