【发布时间】:2019-07-02 00:02:11
【问题描述】:
我有一个烧瓶网络应用程序,它呈现一个在表单中显示多个字段的 Jinja2 模板。该表单表示我的数据库中的两个表,表之间存在一对多关系。
记录类
class Record(db.Base):
__tablename__ = 'metadata_record_version'
id = Column(Integer, primary_key=True)
number = Column(Float, nullable=False)
额外的属性类
class Extra(db.Base):
__tablename__ = 'extra'
id = Column(Integer, primary_key=True)
record_id = Column(Integer, ForeignKey('metadata_record_version.id'), nullable=False)
key = Column(String(256), nullable=False)
value = Column(String, nullable=False)
metadata_record_version = relationship("MetadataRecordVersion")
表单允许用户动态地将更多行添加到包含额外行的表中。用户通过单击表单上调用相关 javascript 函数的 + 和 - 按钮来实现此目的。我的这部分代码运行良好,目前看起来像:
Template.html
<form>
<!-- Other Form attributes here -->
<table id="extra-table">
<tr>
<th class="col-md-4">Property</th>
<th class="col-md-4">Value</th>
<th class="col-md-4"></th>
</tr>
{% for extra in form.extras %}
<tr>
<td>{{ extra.key(class_="form-control") }}</td>
<td>{{ extra.value(class_="form-control") }}</td>
<td>
<button type="button" class="btn btn-danger"
onclick="removeExtraRow(this)">
Remove <i class="fas fa-minus"></i>
</button>
</td>
</tr>
{% endfor %}
<button type="button" class="btn btn-info" onclick="addExtraRow()">
Add Row <i class="fas fa-plus"></i>
</button>
</table>
</form>
<script> Template.html 中的标签
// Function to add a row to the Extra Properties Table
function addExtraRow() {
let table = document.getElementById("extra-table");
let row = table.insertRow(-1);
row.contentEditable = "true";
row.insertCell(0);
row.insertCell(1);
let cell3 = row.insertCell(2);
cell3.innerHTML = "
<button type=\"button\" class=\"btn btn-danger\" onclick=\"removeExtraRow(this)\"> Remove <i class=\"fas fa-minus\"></i> </button>";
}
// Function to remove a row from the extra properties table
function removeExtraRow(x) {
let i = x.parentNode.parentNode["rowIndex"];
let table = document.getElementById("extra-table");
table.deleteRow(i);
}
我面临的问题是正确接收表单数据并将其传递到 WTForms。
如何在 WTForms 中为动态长度表建模?目前,当将一行添加到表中时,它不会正确地将其发布回视图。
当前 form.py
class ExtraForm(Form):
key = StringField('Property')
value = StringField('Value')
class Edit(FlaskForm):
version_number = FloatField('Version Number')
extras = FieldList(FormField(ExtraForm)
编辑:通过使用FieldList(FormField(ExtraForm))添加了关于一对多关系的进展。
【问题讨论】:
标签: python flask sqlalchemy jinja2