如何高效创建大表格-FlaskForms

时间:2019-05-13 08:20:28

标签: python-3.x flask flask-sqlalchemy flask-wtforms

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

@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多个字段,我将如何更改此代码,这样我就不必显式声明每个字段。

1 个答案:

答案 0 :(得分:2)

基于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)