How to empty a numeric value from a form built with WTForm

Luis Milanese

I have this small Flask program. It expects the name and age of the user, and then it prints a message. Really easy, for I'm just getting started with Python and Flask.

from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap 
from flask.ext.wtf import Form 
from wtforms import StringField, IntegerField, SubmitField
from wtforms.validators import Required, Length, NumberRange

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
bootstrap = Bootstrap(app)

class NameForm(Form):
    name = StringField('What is your name?', validators = [Required(), Length(1, 16)])
    age  = IntegerField('How old are you?', validators = [Required(), NumberRange(min=1, max=99, message="Should be between 1 and 99")])

    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
    name = None
    age  = None
    form = NameForm()
    if form.validate_on_submit():
        name = form.name.data
        age  = form.age.data
        form.age.raw_data = None
        form.name.data = ''

    return render_template('index.html', form = form, name = name, age = age)

if __name__ == '__main__':
    app.run(debug = True)

And, for the HTML template, I have: {% extends "bootstrap/base.html" %}

{% block title %}Form Example{% endblock %}

{% block navbar %}
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <a href="{{ url_for('index') }}" class="navbar-brand">Hello</a>
        </div>
    </nav>
{% endblock %}

{% block content %}
    <div class="container">
        <form method="POST" action="">
            {{ form.name.label }} {{ form.name(size=16, class='name-field') }}
            {% for error in form.name.errors %}
                {{ error }}
            {% endfor %}

            <br>

            {{ form.age.label }} {{ form.age(class='age-field') }}
            {% for error in form.age.errors %}
                {{ error }}
            {% endfor %}

            <br />
            {{ form.submit() }}
            {{ form.hidden_tag() }}
        </form>
        {% if name %}
            <h1>Hello, {{ name.capitalize() }}</h1>
            <h2>You're {{ age }} years old.</h2>
        {% endif %}
    </div>
{% endblock %}

My question is, after I submit the form, the name input is emptied but the age input is not. Why? How can I empty a numeric field?

Thanks.

Doobeh

Thanks for the clear question-- the easiest way I can think of to blank the form is just to create it and tell it to ignore the request form data.

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()  # Auto-populates from request data.
    name = None
    age = None
    if form.validate_on_submit():
        name = form.name.data
        age  = form.age.data

        # Lets now create a form, but ignore the request data, so it's empty:
        form = NameForm(formdata=None)
    return render_template('index.html', form = form, name = name, age = age)

Also, I notice you're using Required() that's in the progress of being replaced by DataRequired() and will disappear in WTF v3 so you might want to start using it now, your future self will thank you!

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

How to input unicode character and get its numeric value

来自分类Dev

How to display an empty value in NumericUpDown control?

来自分类Dev

The value of 'form' must inherit from 'BaseModelForm'

来自分类Dev

Is there a in built method from python csv module to enumerate all possible value for a specific column?

来自分类Dev

Updating model data from form value ruby on rails

来自分类Dev

ORA-06502: PL/SQL: numeric or value error: character string buffer too small exception from C# code

来自分类Dev

I want to get numeric data from string. How to do that in python?

来自分类Dev

Any possible way to get the value from form1 to form2 before submitting form2

来自分类Dev

Detect empty value on prompt

来自分类Dev

Is there a built in Kotlin method to apply void function to value?

来自分类Dev

WTForm FormField填充值

来自分类Dev

How to get the total value of to two rand() variables that match on the input value of a text form?

来自分类Dev

MS-Access VBA: How to set field value back to old value if Form_Error event is triggered

来自分类Dev

How to get selective rows from a matrix and form a new matrix in octave?

来自分类Dev

Fast and safe conversion from string to numeric types

来自分类Dev

How to get a value from keyvalue pair list?

来自分类Dev

How to get the value from ArrayList<Object> in android

来自分类Dev

How to Pass a Value From a Window to a UserControl in WPF

来自分类Dev

How to extract value from table function in R

来自分类Dev

How can I merge 2 input values from a form before performing a form action?

来自分类Dev

How can I find out if an data- attribute is set to an empty value?

来自分类Dev

(烧瓶)WTForm呈现了错误的值

来自分类Dev

未验证动态 WTForm 字段

来自分类Dev

Handsontable - I found a bug when copying/pasting a german numeric value

来自分类Dev

PHP is_numeric vs〜(〜(float)$ value)性能和功能

来自分类Dev

How to preserve NULL state in a Boolean sending an empty String from JSP to Action

来自分类Dev

Capybara form value set with cocoon

来自分类Dev

Resetting a Bacon property on value changed to empty

来自分类Dev

IF NOT EXIST insert ELSE IF update ELSE IF EXISTS and is not Numeric DELETE From WHERE

Related 相关文章

  1. 1

    How to input unicode character and get its numeric value

  2. 2

    How to display an empty value in NumericUpDown control?

  3. 3

    The value of 'form' must inherit from 'BaseModelForm'

  4. 4

    Is there a in built method from python csv module to enumerate all possible value for a specific column?

  5. 5

    Updating model data from form value ruby on rails

  6. 6

    ORA-06502: PL/SQL: numeric or value error: character string buffer too small exception from C# code

  7. 7

    I want to get numeric data from string. How to do that in python?

  8. 8

    Any possible way to get the value from form1 to form2 before submitting form2

  9. 9

    Detect empty value on prompt

  10. 10

    Is there a built in Kotlin method to apply void function to value?

  11. 11

    WTForm FormField填充值

  12. 12

    How to get the total value of to two rand() variables that match on the input value of a text form?

  13. 13

    MS-Access VBA: How to set field value back to old value if Form_Error event is triggered

  14. 14

    How to get selective rows from a matrix and form a new matrix in octave?

  15. 15

    Fast and safe conversion from string to numeric types

  16. 16

    How to get a value from keyvalue pair list?

  17. 17

    How to get the value from ArrayList<Object> in android

  18. 18

    How to Pass a Value From a Window to a UserControl in WPF

  19. 19

    How to extract value from table function in R

  20. 20

    How can I merge 2 input values from a form before performing a form action?

  21. 21

    How can I find out if an data- attribute is set to an empty value?

  22. 22

    (烧瓶)WTForm呈现了错误的值

  23. 23

    未验证动态 WTForm 字段

  24. 24

    Handsontable - I found a bug when copying/pasting a german numeric value

  25. 25

    PHP is_numeric vs〜(〜(float)$ value)性能和功能

  26. 26

    How to preserve NULL state in a Boolean sending an empty String from JSP to Action

  27. 27

    Capybara form value set with cocoon

  28. 28

    Resetting a Bacon property on value changed to empty

  29. 29

    IF NOT EXIST insert ELSE IF update ELSE IF EXISTS and is not Numeric DELETE From WHERE

热门标签

归档