如何自定义flask-wtf表单中的字段

时间:2016-11-20 03:05:14

标签: python flask wtforms flask-wtforms

那里。 我定义了一个名为LoginForm的类:

class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Length(5, 64), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember me')
    submit = SubmitField('Log In')

然后我在模板login.html

中渲染它
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}

看起来如上: enter image description here

我认为这有点难看。所以,我以正常的方式渲染字段:

<form action="" method="POST" role="form" class="form">
    {{ form.hidden_tag() }} {{ wtf.form_errors(form, hiddens="only") }}
    <div class="form-group  required">
        <label class="control-label" for="email">Email</label>
        {{ form.email(class="form-control",id="email",required="required",type="text",value="",placeholder="Enter email") }}
    </div>
    <div class="form-group  required">
        <label class="control-label" for="password">Password</label>
        {{ form.password(class="form-control",id="password",required="required",type="password",value="",placeholder="Enter email") }}
    </div>
    <div class="checkbox">
        <label>
            <input id="remember_me" name="remember_me" type="checkbox" value="y"> Remember me
        </label>
    </div>
    {{ form.submit(class="btn btn-success btn-block") }}
    <a href="{{ url_for('auth.register') }}" class="btn btn-danger btn-block" role="button">Register</a>
</form>

enter image description here

现在它同意我的看法。但我遇到了一个问题:当我点击绿色登录按钮时,它不会验证数据(如电子邮件地址的格式)。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

首先我认为它没有验证。感谢@BurhanKhalid提醒我。 它只是没有显示错误。我改变了代码并且它有效。

{% if form.email.errors %}
    <div class="form-group  required has-error">
        {{ form.email(class="form-control",id="email",required='required',type="text",value="",placeholder="Enter email") }}
        {% for error in form.email.errors %}
        <p class="help-block">{{ error }}</p>
        {% endfor %}
{% else %}
    <div class="form-group  required">
    {{ form.email(class="form-control",id="email",required='required',type="text",value="",placeholder="Enter email") }}
{% endif %}
    </div>