2 回答
TA贡献1816条经验 获得超4个赞
这是未经测试的。看看它是否有效:
for i in range (1,5):
if form['contact' + str(i)].data:
contact = Contacts(content=form['contact' + str(i)].data)
db.session.add(contact)
db.session.commit()
TA贡献1810条经验 获得超5个赞
我还没有测试过这个,但它应该可以工作,或者至少让你走上正确的道路,了解如何进一步压缩它。
@app.route('/admin/media-kontaktai', methods=['GET', 'POST'])
@login_required
def media_contacts():
form = MediaContactsForm()
if request.method == 'POST':
if form.validate_on_submit():
try:
# You can just delete all records in one go instead of
# wasting time iterating and checking lengths
db.session.query(Contacts).delete()
db.session.commit()
except:
db.session.rollback()
# I am iterating fields in the form that have data
# so we don't need multiple if statements
for field in [field for field in form if field.data]:
contact = Contacts(content=field.data)
db.session.add(contact)
db.session.commit()
flash('Informacija atnaujinta!', 'success')
return redirect(url_for('media_contacts'))
else:
for field, index in enumerate(form):
for contact in Contacts.query.all():
field.data = contact.content
contacts = Contacts.query.all()
return render_template('a-media-kontaktai.html', title='Media ir kontaktai', form=form, contacts=contacts)
添加回答
举报