Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - flask-wtforms field required

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') }}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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="">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...