FlaskWTF验证器可防止隐藏表单字段

时间:2016-02-28 03:20:14

标签: python forms flask

我正在尝试使用烧瓶构建并提交表单。我的烧瓶登记表功能:

表格类:

tvann@tvann-pi2:~/node/serial$ node app
open
sending: ;402'\PT\GC1.FE02:CV'980B
results 26
data received: 00A
^C
tvann@tvann-pi2:~/node/serial$ node app
open
sending: ;402'\PT\GC1.FE02:CV'980B
results 26
data received: 65
data received: 0000A3
data received: D0
^C
tvann@tvann-pi2:~/node/serial$ node app
open
sending: ;402'\PT\GC1.FE02:CV'980B
results 26
data received: A
data received: 3D0
^C
tvann@tvann-pi2:~/node/serial$ node app
open
sending: ;402'\PT\GC1.FE02:CV'980B
results 26
data received: 4E
^C
tvann@tvann-pi2:~/node/serial$ node app
open
sending: ;402'\PT\GC1.FE02:CV'980B
results 26
data received: 4E0000A

jinja2形式:

class RegisterForm(Form):
    username = StringField('Username', validators=[DataRequired(), 
    email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)])

注册功能:

<h1>Register</h1>
<br/>
<form id="registerForm" class="form form-register" method="POST" action="" role="form">
        {{ form.hidden_tag() }}
        {% for field in form %}
            {% if field.data==None %}
                {{ render_field(field) }}
            {% endif %}
        {% endfor %}

我的计划是只显示我需要填写的字段。在这种情况下,我已经收到了电子邮件,所以我不想显示它,但有时我会需要填写电子邮件。这与Get请求按预期工作,但在发布结果时我得到:

@blueprint.route("/register/", defaults={'token': ''}, methods=['GET', 'POST'])
@blueprint.route("/register/<token>", methods=['GET', 'POST'])
def register(token):
    email = confirm_token(token)
    form = RegisterForm(request.form, csrf_enabled=False, email=email)
    if form.validate_on_submit():
    .......

我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:1)

最好在服务器端有条件地删除该字段。

class MagazineIssueForm(Form):
    title  = StringField()
    year   = IntegerField('Year')
    month  = SelectField(choices=MONTHS)

def edit_issue():
    publication = get_something_from_db()
    form = MagazineIssueForm(...)

    if publication.frequency == 'annual':
        del form.month

    # render our form

请参阅:http://wtforms.readthedocs.org/en/latest/specific_problems.html#removing-fields-per-instance