gpt4 book ai didi

python-3.x - 如何高效创建大表格-FlaskForms

转载 作者:行者123 更新时间:2023-12-03 16:26:09 25 4
gpt4 key购买 nike

因此,我有一个很大的更新表单端点,我已经尝试了一些方法来动态创建它以压缩我的代码,但是我似乎无法弄清楚。

@customers.route("/<int:customer_id>/update_customer", methods=['GET', 'POST'])
# not programmatic - needs work - I do not like this
def update_customer(customer_id):
post = Post.query.get_or_404(customer_id)
if post.author != current_user:
abort(403)
form = CustomerForm()
if form.validate_on_submit():
post.tpi_name = form.tpi_name.data
post.tpi_ref = form.tpi_ref.data
post.company_name = form.company_name.data
post.company_type = form.company_type.data
post.company_reg = form.company_reg.data
post.sic_code = form.sic_code.data
post.vat_number = form.vat_number.data
db.session.commit()
flash("That customer's record has been updated!", 'success')
return redirect(url_for('customers.view_customer', customer_id=post.id))
elif request.method == 'GET':
form.tpi_name.data = post.tpi_name
form.tpi_ref.data = post.tpi_ref
form.company_name.data = post.company_name
form.company_type.data = post.company_type
form.company_reg.data = post.company_reg
form.sic_code.data = post.sic_code
form.vat_number.data = post.vat_number
return render_template('customers/customers.html', form=form, username=current_user.username,image_file=current_user.image_file, email=current_user.email)


所以说,如果表单中有100多个字段,我将如何更改此代码,这样我就不必显式声明每个字段。

最佳答案

根据pjcunningham的答案,并查看wtform docs,我发现了这段代码:

def edit_profile(request):
user = User.objects.get(pk=request.session['userid'])
form = EditProfileForm(request.POST, obj=user)

if request.POST and form.validate():
form.populate_obj(user)
user.save()
return redirect('/home')
return render_to_response('edit_profile.html', form=form)


基于此,我想您想编写以下代码:

if form.validate_on_submit():
form.populate_obj(post)
db.session.commit()

flash("That customer's record has been updated!", 'success')
return redirect(url_for('customers.view_customer', customer_id=post.id))


对于代码的第二部分(“ GET”分支),这取决于您的意图。创建表单时,可以使用来自对象的数据填充表单:

form = CustomerForm(obj=post)

关于python-3.x - 如何高效创建大表格-FlaskForms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com