0

我正在尝试提交从 FiedList 生成的字段,但出现错误: AttributeError: 'str' object has no attribute 'data'

我想要做的是将字段列表添加到数据库中,然后我可以检索并显示在页面上。

#App.py

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MainSubscriptionForm()
    if form.validate_on_submit():
        for x in form.subscription:
            sub = Subscription(company=x.company.data, description=x.description.data)
            db.session.add(sub)
            db.session.commit()
    elif request.method == 'GET':
        list = Subscription.query.all()
    return render_template('index.html', title="Home", form=form, list=list)
#forms.py

class SubscriptionForm(FlaskForm):
    company = StringField(('Company'), validators=[DataRequired(), Length(min=0, max=20)])
    description = StringField(('Description'), validators=[Length(min=0, max=120)])
    save = SubmitField('Save')

class MainSubscriptionForm(FlaskForm):
    subscription = FieldList(FormField(SubscriptionForm), min_entries=1)

#models.py

class Subscription(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    company = db.Column(db.String(20))
    description = db.Column(db.String(120))
#index.html

{% extends "base.html" %}
{% from 'bootstrap/form.html' import render_form_row %}
{% block content %}
    <form method="post">
    {{ form.csrf_token() }}
       {% for sub in form.subscription %}
            {{ render_form_row(sub) }}
        {% endfor %}
    </form>
    {{ list }}
{% endblock %}

4

1 回答 1

0

问题是正在发送字典,因此它在以下行崩溃:

sub = Subscription(company=x.company.data, description=x.description.data)

解决方案是按以下方式获取键值:

sub = Subscription(company=x.data['company'], description=x.data['description'])

于 2021-05-28T07:11:17.950 回答