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
200 views
in Technique[技术] by (71.8m points)

python - Flask and WTForms - how FlaskForm works?

I am learning Flask and I have trouble understanding FlaskForm from Flask-WTF. This example is from the book Flask Web Development: Developing Web Applications with Python, Miguel Grinberg. Code below.

hello.py

class NameForm(FlaskForm):
    name = StringField('What is your name?', validators=[DataRequired()])
    submit = SubmitField('Submit')
 
@app.route('/', methods=['GET', 'POST'])
def index():
    name = None
    form = NameForm()
    if form.validate_on_submit():
        name = form.name.data
    return render_template('index.html', form=form, name=name)

index.html

{% import "bootstrap/wtf.html" as wtf %}
{% block page_content %}
<div class="page-header">
    <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}

This simple application get name from the user and displays a personalized message. Suppose I have entered my name and click submit button. How it's possible that entered name is recived from the form object (instance of NameForm) and send to render

name = form.name.data

when before this, new instance of NameForm is assigned to the form variable?

form = NameForm()
question from:https://stackoverflow.com/questions/65861937/flask-and-wtforms-how-flaskform-works

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

1 Reply

0 votes
by (71.8m points)

Without FlaskForm. You can get the name that submitted by user using Flask.request like following:

@app.route('/', methods=['GET', 'POST'])
def index():
    name = None
    name = request.form.get('name', None)

(you need append from Flask import request )

This means any library can get request values through the Flask.request object when that called from handler. And this is why FlaskForm does not need any arguments to get requested values (as long as it is called from a request handler).


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

...