asyndrige
asyndrige

Reputation: 592

Flask form processing

What is the correct way processing of forms, which are optional and use no validation?

#forms.py:
class PageForm(Form):
    field1 = TextField('field1')
    field2 = SelectField('field2', choices=choices)

#views.py
def page():
    if request.method == 'POST':
        if request.form.get('field1'):
            #some action
        if request.form.get('field2'):
            #some other action

Is it okay to process forms like this? Looks lousy.

Upvotes: 2

Views: 801

Answers (1)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

Overall, such handling is correct if form validation is not required. Just one suggestion:

Use the method param of the app.route decorator:

@app.route('/', methods=['POST',])

After decoration with method==['POST',] declared, your view accepts only POST requests and you could strip the if statement.

Also, you could consider adding a form variable, so your code would become more verbose, and not planned data from request.form would be stripped:

form = PageForm(request.form)
# Than, access fields as form.<FIELD_NAME>.data

Upvotes: 2

Related Questions