Z
Z
zlodiak2019-04-23 10:17:41
Python
zlodiak, 2019-04-23 10:17:41

Why is the form not valid?

There is a common form. I can't check its validity after submitting it. Please help me figure it out.
form class:

class SearchForm(FlaskForm):
    searcher = SelectField(
        'Поисковик', 
        choices=[(item.id, item.searcher) for item in Searcher.query.all()],
        validators=[DataRequired()]
    )
    query = StringField('Запрос', validators=[DataRequired()])
    submit = SubmitField('Найти')

relevant markup:
{% extends "base.html" %}

{% block content %}
    <form action="/search" method="POST" novalidate>
        {{ search_form.hidden_tag() }}

        <div>
            {{ search_form.searcher }}
            {{ search_form.query(size=32) }}
            {{ search_form.submit() }}
        </div>
    </form>
{% endblock %}

After submitting in the chrome debugger, you can see that the POST request leaves with the query, searcher, csrf_token values ​​filled in. Return code 200
route:
@app.route('/', methods=['GET', 'POST'])
@app.route('/search', methods=['GET', 'POST'])
def search():
    print(request.form)
    search_form = SearchForm()
    if request.method == 'POST' and search_form.validate_on_submit():
        print('form is valid')
    else:
        print('form is not valid')
    return render_template('search.html', title='Поиск', search_form=search_form)

The problem is visible in the console output:
flask run
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
ImmutableMultiDict([])
form is not valid
127.0.0.1 - - [23/Apr/2019 10:01:50] "GET /search HTTP/1.1" 200 -
ImmutableMultiDict([('submit', 'Найти'), ('searcher', '1'), ('query', 'gg'), ('csrf_token', 'ImFiMzFjM2IzOWJlNTU2YjBlYjcxNzA3MTUyYzMxZGUwYzdmNTk5YjQi.XL64Xg.EYYAUzvlpnlYScpPqt5Z8xXVvUg')])
form is not valid
127.0.0.1 - - [23/Apr/2019 10:01:53] "POST /search HTTP/1.1" 200 -

It can be seen that the first time (when the form is rendered), "form is not valid" is displayed. And after the submit, the route again displays "form is not valid", although the form is valid and there is a csrf token
Full code here

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pcdesign, 2019-04-23
@zlodiak

if request.method == 'POST' and search_form.validate_on_submit():

Because of this line.
If the request is not POST, but GET, then each time we will get 'form is not valid'
It should be something like this:
if request.method == 'POST':
    if search_form.validate_on_submit():
        print('form is valid')
    else:
        print('form is not valid')

Also try adding str like this:
choices=[(str(item.id), item.searcher) for item in Searcher.query.all()]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question