Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic form fields in flask.request.form

Tags:

I've looked through the documentation, but for the life of me, I can't figure out how the request.form object in Flask is populated. The documentation says that it's filled with parsed form data from POST or PUT requests, but my form is dynamic so I don't necessarily know what fields exist when the POST request is sent - though I want to make sure I add the information from these fields to the database.

Some of the fields in the form are always there, but there will also be any number of extra fields from a list of about 60. How should I go about figuring out which of these additional fields are in the request and how should I get the data from them?

EDIT: My specific problem has been solved, but it's still worth asking how the request.form dictionary is populated. I found out the hard way that if a checkbox input is unchecked, there is no key added to the dictionary under its name, and trying to get the value of a key that does not exist from the dictionary results in a rather confusing and cryptic HTTP 400 BAD REQUEST error.

like image 807
Chase Sandmann Avatar asked Jul 19 '13 17:07

Chase Sandmann


1 Answers

request.form returns a MultiDict object. Basically, it means that for 1 key, you could have multiple values. If you want to test what your form POST looks like, just do a quick print statement as follows

f = request.form
for key in f.keys():
    for value in f.getlist(key):
        print key,":",value

If you read the documentation for MultiDict, it says

"A MultiDict is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key."

http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict

like image 87
codegeek Avatar answered Sep 28 '22 05:09

codegeek