[Flask] flask-wtf form and server-side validation

Kyle Lawlor klawlor419 at gmail.com
Sat Feb 6 14:33:02 EST 2016


Is there a way to directly pass json data from a form, using
request.get_json() into a wtform object at instantiation?

Basically what I want would be something like:

    validation_form = MyForm(json_form_data = request.get_json())
    validation_form.validate()
    ... do stuff depending on validation ...

Details:

I'm trying to get the data from a form to server-side in order to validate
it with wtforms. (I pass the data via AJAX from a wtform inheriting the
flask-wtf Form object.)

I am using $("#targetForm").serializeArray() and passing that as the data:
attribute in the ajax call. I pass it to the server as "application/json"
type and retrieve it in the Flask view function with request.get_json().

Thus far, I am able to validate the form with something like:


    validation_form = create_modal_form(item, for_validation = True,
                                                               csrf_token =
form_data['csrf_token'],
                                                               sides =
form_data['sides'])


Sparing some of the details, create_modal_form does basically this:


    def create_modal_form(item_object, prefix_string = '', for_validation =
False, **kwargs):
        class ModalForm(Form):

        ... functionally declare a bunch of fields dependent upon
item_object properties ...

        if not for_validation:
            return ModalForm(prefix=prefix_string)
        else:
            return ModalForm(formdata=None, **kwargs)


The important thing is that when I am looking to validate, I pass in the
data to the wtform object instantiation as *kwargs. (Like csrf_token and
sides in the call above and it works.)

Any advice and comments appreciated!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20160206/52c66a21/attachment.html>


More information about the Flask mailing list