简体   繁体   English

WTForms,如何将JSON数据附加到请求

[英]WTForms, how to attach JSON data to the request

I'm bulding a form with WTForms for a Flask application. 我正在为Flask应用程序构建带有WTForms的表单。 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. 此表单的las字段是与Google PlacesAPI一起使用的地址字段,因此它将自动完成用户在该字段中介绍的地址。

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. 我希望能够保存用户选择地址时此PlacesAPI生成的所有数据,但是我一直在努力寻找将数据发送到服务器的正确方法。

I have a Flask with MongoDB as backend. 我有一个MongoDB作为后端的烧瓶。

What I have tried 我尝试过的

  1. AJAX 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. 我使用Jquery Ajax方法提交了表单,并通过在项目中添加WTF-JSON对其进行了验证,它对Form类和某些方法进行了修补,因此它可以将JSON处理为***。

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 我可以添加一个隐藏的输入字段,在其中将所有地址JSON添加为字符串,然后在后端处理它

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. 非常感谢您的所有帮助。

Option # 1 is the best option considering the scenarios you have explained. 考虑到您所说明的方案,选项1是最佳选择。 There should not be any problems in re-directing the user to form validation page as you can manage it through XHR. 将用户重定向到表单验证页面应该没有任何问题,因为您可以通过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. 请根据您的功能需要使用is_xhr ,但我建议您使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM