I have a flask web app that renders a Jinja2 template displaying multiple fields in a form. The form represents two tables in my database with a one-to-many relationship between the tables.
Record Class
class Record(db.Base):
__tablename__ = 'metadata_record_version'
id = Column(Integer, primary_key=True)
number = Column(Float, nullable=False)
Extra Property Class
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")
The form allows the user to dynamically add more rows to a table containing the rows of extra. The user acheives this by clicking the + and - buttons on the form that call the relevant javascript functions. This part of my code works well and currently looks like:
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> tag in 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);
}
The issue im facing is correctly receiving back the form data and passing it in WTForms.
How do I model in WTForms the dynamic length table? Currently when a row is added to the table it doesn't correctly post it back to the view.
Current form.py
class ExtraForm(Form):
key = StringField('Property')
value = StringField('Value')
class Edit(FlaskForm):
version_number = FloatField('Version Number')
extras = FieldList(FormField(ExtraForm)
Edit: Added progress with regards to one-to-many relationship by use of FieldList(FormField(ExtraForm)).