Search code examples
ajaxflaskwtformsflask-wtformswtforms-json

WTForms, how to attach JSON data to the request


I'm bulding a form with WTForms for a Flask application. This form's las field is an address field that works with google PlacesAPI, so it autocompletes the address the user is introducing in that field.

I want to be able to save all the data this PlacesAPI generates when the user selects an address, but I'm struggling to find a proper way to send that data to the server.

I have a Flask with MongoDB as backend.

What I have tried

  1. AJAX

I submited the form with Jquery Ajax method, I validated it by adding WTF-JSON to my project, it monkeypatches the Form class and some methods so it can process JSON as ***kwargs.

Problem: this leaves me without being able to easily redirect the user on form validation.

  1. Adding hidden input field

I can add a hidden input field where I add all the address JSON as a string and then process it in my backend

Problem: Somehow this simes hacky, I was wondering if there is a better way

Question

What would be the right way to do this? It's the first time I've tried, so I'm pretty sure there must be a way I'm missing here. Thanks a lot for all your help.


Solution

  • Option # 1 is the best option considering the scenarios you have explained. There should not be any problems in re-directing the user to form validation page as you can manage it through XHR. Here is what I can suggest

    @catalog.route('/')
    @catalog.route('/your_page')
    def home():
        if request.is_xhr:
            ## Here you can call the def and store the addresses
            addresses = Address.query.all() 
            json_addresses jsonify({'addresses': addresses)})
            return render_template('your_form_page.html', json_addresses)    
    

    While rendering the template page you pass few more parameters such as validation messages.

    Please use is_xhr as per the need of your functionality but I recommend it.