wtforms-sqlalchemy 的 QuerySelectField 功能

问题描述 投票:0回答:1

我正在尝试将数据从 Flask-SQLAlchemy 数据库自动填充到 FlaskForm。这是我的代码片段:

class Products(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    cost = db.Column(db.Float(), nullable=False)
    price = db.Column(db.Float(), nullable=False)
    category = db.Column(db.String(20), nullable=False)
    details = db.Column(db.String(255), nullable=True)
    quantity = db.Column(db.Integer(), nullable=False, default=0)
    threshold = db.Column(db.Integer(), nullable=False, default=0)
    prod_img = db.Column(db.String(20), nullable=False, default='prod_img.jpg')
    disc_amt = db.Column(db.Float(), nullable=True)
    disc_percent = db.Column(db.Float(), nullable=True)
    disc_conditions = db.Column(db.String(255), nullable=True)
    promo_start = db.Column(db.DateTime(), nullable=True)
    promo_end = db.Column(db.DateTime(), nullable=True)

    def __repr__(self):
        return f"Products('{self.name}', '{self.price}', '{self.quantity}')"

我想将此模型中的产品自动填充为接受购买的表单。这是我的表格:

from flask_wtf import FlaskForm
from wtforms import SubmitField, FloatField, IntegerField, FieldList, FormField, DateField
from wtforms.validators import DataRequired
from wtforms_sqlalchemy.fields import QuerySelectField
from root.models import Products, Suppliers

class ProductForm(FlaskForm):
    name = QuerySelectField('Product Name', validators=[DataRequired()], query_factory=lambda: Products.query.all(), get_label='name')
    quantity = IntegerField('Quantity', validators=[DataRequired()])
    total = FloatField('Total Cost', validators=[DataRequired()])
    submit = SubmitField('Add Product')


class ReceiptForm(FlaskForm):
    date = DateField('Date', validators=[DataRequired()])
    supplier = QuerySelectField('Supplier', validators=[DataRequired()], query_factory=lambda: Suppliers.query.all(), get_label='company')
    products = FieldList(FormField(ProductForm), min_entries=1)
    submit = SubmitField('Add Purchase')

这是我的路线:

from flask import Blueprint, render_template
from root.models import Products
from root.purchases.forms import ReceiptForm


purchases = Blueprint('purchases', __name__)


@purchases.route('/add_receipt/', methods=['GET', 'POST'])
def add_receipt():
    form = ReceiptForm()
    print(type(form.products[0].name))  # Print the type of the 'name' field
    print(form.products[0].name)  # Print the 'name' field itself
    if form.validate_on_submit():
        pass
    return render_template('add_purchases.html', form=form)

最后是我的模板片段:

<div class="card">
        <div class="card-header"><h2 class="lead">Add Purchases</h2></div>
        <div class="card-body">
            <form action="" id="purchase-form">
                {{ form.hidden_tag() }}
                <div class="mb-3">
                    {{ form.date.label }} {{ form.date(class="form-control") }}
                </div>
                <div class="mb-3">
                    {{ form.supplier.label }} {{ form.supplier(class="form-control") }}
                </div>
                {% for product_form in form.products %}
                    <div class="mb-3">
                        {{ product_form.name.label }} {{ product_form.name(class="form-control") }}
                        {{ product_form.quantity.label }} {{ product_form.quantity(class="form-control") }}
                        {{ product_form.total.label }} {{ product_form.total(class="form-control") }}
                    </div>
                {% endfor %}
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>

当我运行此代码时,我不断收到以下错误: 127.0.0.1 - - [2023 年 9 月 09 日 16:24:36] “GET /add_receipt/ HTTP/1.1” 500 - 回溯(最近一次调用最后一次): 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask pp.py",第 2213 行,在 call 中 返回 self.wsgi_app(环境,start_response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask pp.py",第 2193 行,在 wsgi_app 中 响应 = self.handle_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask pp.py",第 2190 行,在 wsgi_app 中 响应 = self.full_dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask pp.py",第 1486 行,在 full_dispatch_request 中 rv = self.handle_user_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask pp.py",第 1484 行,在 full_dispatch_request 中 rv = self.dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask pp.py",第 1469 行,dispatch_request 返回 self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ 文件“x:\Code-FLASK\Projects 电子尾部位置 oot\购买 outes.py”,第 16 行,在 add_receipt 中 返回 render_template('add_purchases.html', form=form) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask emplating.py",第 151 行,在 render_template 中 返回_render(应用程序,模板,上下文) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages lask emplating.py",第 132 行,在 _render 中 rv = template.render(上下文) ^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages\jinja2 nvironment.py”,第 1301 行,渲染中 self.environment.handle_exception() 文件“X:\代码-FLASK\项目 etail_pos irt\Lib\site-packages\jinja2 nvironment.py”,第 936 行,handle_exception 引发 rewrite_traceback_stack(源=源) 文件“x:\Code-FLASK\Projects 电子尾部位置 oot emplates dd_purchases.html",第 1 行,在顶级模板代码中 {% 扩展 'base.html' %} 文件“x:\Code-FLASK\Projects 电子尾部位置 oot emplates ase.html”,第 162 行,顶级模板代码 {% 块内容 %}{% 结束块内容 %} 文件“x:\Code-FLASK\Projects 电子尾部位置 oot emplates dd_purchases.html”,第 30 行,“内容”块中 {{ Product_form.name.label }} {{ Product_form.name(class="form-control") }} 类型错误:“str”对象不可调用 127.0.0.1 - - [09/Sep/2023 16:24:36] “GET /add_receipt/?debugger=yes&cmd=resource&f=style.css HTTP/1.1”304 - 127.0.0.1 - - [09/Sep/2023 16:24:36]“GET /add_receipt/?debugger=yes&cmd=resource&f=debugger.js HTTP/1.1”304 - 127.0.0.1 - - [09/Sep/2023 16:24:36]“GET /add_receipt/?debugger=yes&cmd=resource&f=console.png HTTP/1.1”304 - 127.0.0.1 - - [09/Sep/2023 16:24:37]“GET /add_receipt/?debugger=yes&cmd=resource&f=console.png HTTP/1.1”304 -

有人可以告诉我哪里出错了吗?

我也尝试过使用强制函数,但这又给我带来了一大堆错误。

python flask flask-sqlalchemy wtforms
1个回答
0
投票

发生错误是因为

product_form.name
是一个字符串,而不是您想要的
QuerySelectField

出于调试目的,您可以在渲染模板之前打印

form.products[0].name
以检查其包含的内容。它应该是一个字段对象,而不是
string

© www.soinside.com 2019 - 2024. All rights reserved.