为什么我的WTForms-JSON表单没有正确更新?

时间:2015-06-09 19:09:33

标签: python flask wtforms wtforms-json

我正在开发一个读取JSON的网页,并使用WTForms-JSON以表格形式呈现它。提交表单时,form.data尚未更新。为什么这不起作用?

views.py

from flask import render_template, flash, redirect, request
from app import app
from .forms import PolicyForm
import json
import urllib2

@app.route('/policy', methods=['GET', 'POST'])
def policy():
    url = 'http://dcdemoappsrv1:8081/direct/policy?policyNumber=000000005&everything=true&discounts=true&coverages=true&vehicles=true&nonDescribedVehicle=true&applicant=true&drivers=true&namedInsureds=true&additionalListedInsureds=true'
    response = urllib2.urlopen(url).read()
    pol_json = json.loads(response) 

    form = PolicyForm.from_json(pol_json)

    if form.validate_on_submit():
        flash('data=%s' % str(form.data))
        flash('form pol no =%s' % str(form.policyNumber.data))
        return redirect('/index')

    flash('inital data=%s' % str(form.data))
    return render_template('policy.html',  title='Policy Form', form=form)

forms.py

from wtforms import Form
from wtforms.fields import BooleanField, StringField, TextField, FloatField, FormField, IntegerField, DateField, SubmitField
from wtforms.validators import DataRequired, InputRequired

class Address(Form):
    street = TextField('Street', validators=[InputRequired()])
    street2 = TextField('Street2')
    city = TextField('City', validators=[InputRequired()])
    state = TextField('State', validators=[InputRequired()])
    zip = TextField('Zip', validators=[InputRequired()])
    county = TextField('County', validators=[InputRequired()])
    latitude = FloatField('Latitude')
    longitude = FloatField('Longitude')
    id = StringField('ID')

class Applicant(Form):
    firstName = TextField('First Name', validators=[InputRequired()])
    lastName = TextField('Last Name', validators=[InputRequired()])
    birthDate = DateField('Birth Date', validators=[InputRequired()])
    age = IntegerField('Age', validators=[InputRequired()])
    id = StringField('ID')

class PolicyForm(Form):
    policyNumber = TextField('Policy Number')
    applicant = FormField(Applicant, label='Applicant')
    address = FormField(Address, label='Address')
<!-- extend from base layout -->
{% extends "base.html" %}

{% block content %}
  <h1>Policy</h1>
  {%  import "__formhelpers.html" as forms %}
<form action="/policy" method="POST" name='policy'>
{{ forms.render(form) }}
<p><input type="Submit" value="Update Policy"></p>
</form>
{% endblock %}

formhelpers.html

{% macro render(form) %}
<dl>
{% for field in form if field.type not in ["HiddenField", "CSRFTokenField"] %}
    <dt>{{ field.label }} </dt>
    <dd>{{ field }}
    {% if field.errors %}
        <ul class="errors">
        {% for error in field.errors %}
            <li>{{error}}</li>
        {% endfor %}
        </ul>
    {% endif %}</dd>
{% endfor %}
</dl>
{{ form.hidden_tag() }}
{% endmacro %}

1 个答案:

答案 0 :(得分:2)

您始终使用远程JSON数据填充表单。您只应在首次提交表单时执行此操作,而不是在处理提交的数据时执行此操作。

# ...
if not form.is_submitted():
    data = json.load(urllib2.urlopen(url))
    form = PolicyForm.from_json(data)
else:
    form = PolicyForm()  # will populate from submitted data

if form.validate_on_submit():
# ...