flask-wtforms field required

谁说胖子不能爱 提交于 2019-11-26 14:52:07

问题


how i can add tag required on this flask code :

{{ form.youtube_href(type='url', class='form-control') }}

actual output is :

<input class="form-control" id="youtube_href" name="youtube_href" value="" type="url">

need this output bat give error :

<input class="form-control" id="youtube_href" name="youtube_href" value="" type="url" required>

im tried this bat give error :

{{ form.youtube_href(type='url', class='form-control', 'required') }}

回答1:


As of WTForms 2.2 (June 2nd, 2018), fields now render the required attribute if they have a validator that sets the required flag, such as DataRequired and InputRequired. If for some reason you don't want to render the attribute, you can pass required=False. Or if you want to disable all browser validation, you can set the novalidate attribute in the form tag. In general you should prefer to leave browser validation enabled, because it prevents a request/response for simple validation, which is desirable.


You are passing a positional argument after keyword arguments, which is a syntax error. Instead, pass required=True, which will set a bare attribute on the tag. Check the flags on a field to see if a Required validator was set: field.flags.required is a boolean. Create a URLField rather than passing the type manually.

from flask_wtf import Form
from wtforms.fields.html5 import URLField
from wtforms.validators import InputRequired

class MyForm(Form):
    youtube_href = URLField(validators=[InputRequired()])

form = MyForm()
print(form.youtube_href(required=form.youtube_href.flags.required))
# <input id="youtube_href" name="youtube_href" required type="url" value="">



回答2:


To those who simply want to add the required attribute to their html input, this can be accomplished by following the comment mentioned by Raja Simon above. Simply call your field name in your template with required='required' Example:

<form>
  ...
  {{myform.my_name_field(required='required')}}
  {{myform.my_email_field(required='required')}}
  ...
</form>

The Above code will result in fields like so:

<input id="my_name_field" name="my_name_field" required="required" type="text" value="">


来源:https://stackoverflow.com/questions/33307888/flask-wtforms-field-required

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