Flask-WTForms: how to check if a field is required?

拟墨画扇 提交于 2019-12-06 04:20:19

问题


I defined a form in the following way:

class LoginForm(Form):
    login = EmailField(u'Email address', [required(), length(min=5, max=2048), validators.Email()])
    password = PasswordField(u'Password', [required(), length(min=6, max=50)])
    next = HiddenField()
    remember = BooleanField('Remember me')
    submit = SubmitField('Login')

Then I'm writing a generic macro in Jinja2 to render the form fields and I would like to do something like:

{% if field.is_required() %}
  {{ field.label(class_='required') }}
{% else %}
  {{ field.label() }}
{% endif %}

So... is there a way to see if a field is required?


回答1:


Validators can set flags which you can check for:

{% if field.flags.required %}field.label(class_='required'){% endif %}


来源:https://stackoverflow.com/questions/16678317/flask-wtforms-how-to-check-if-a-field-is-required

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