Python QuerySelectField 和 request.form 返回字典键,而不是字典值

标签 python sqlite flask sqlalchemy wtforms

我还不是程序员(正在研究它 - 这是我的第一个大项目),对于乱七八糟的代码深表歉意。

我在使用 QuerySelectField 时遇到一些问题和 request.form['form_field_name']从 SQlite 表中提取数据并将其放入另一个表中。

我正在尝试从 name 获取数据Post 中的列模型填充 actual_amount_name ActualPost 中的列模型,但我认为我实际上是在提取字典键。

这些是我正在使用的 2 个模型/表:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(30), nullable=False, default='planned')
    category = db.Column(db.String(30), nullable=False, default=None)
    name = db.Column(db.String(30), nullable=True)
    planned_amount_month = db.Column(db.Float, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    date_period = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    comments = db.Column(db.Text, nullable=True)

    def __repr__(self):
        return f"Post('{self.title}, '{self.category}'\
        , '{self.name}', '{self.planned_amount_month}'\
        , '{self.date_period}', '{self.comments}')"

#the function below queries the above model and passes the data to the QuerySelectField
def db_query():
    return Post.query

class ActualPost(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(30), nullable=False, default='actual')
    category = db.Column(db.String(30), nullable=False, default=)
    actual_amount_name = db.Column(db.String(30), nullable=True)
    actual_amount = db.Column(db.Float, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    comments = db.Column(db.Text, nullable=True)

    def __repr__(self):
        return f"ActualPost('{self.title}, '{self.category}'\
        , '{self.actual_amount_name}', '{self.actual_amount}'\
        , '{self.date_posted}', '{self.comments}')"

现在 forms :

Post型号 我有一个名为 name 的专栏.此字段中的数据由用户使用 WTForms 添加(下面类中的 name 字段):

class PostForm(FlaskForm):
    title = HiddenField('Please enter the monthly Planned Amount details below:'\
           ,default='planned')
    category = SelectField('Category', choices=[('savings', 'Savings')\
               ,('income', 'Income'), ('expenses', 'Expense')]\
               ,validators=[DataRequired()])
    name = StringField('Name', validators=[DataRequired()])
    planned_amount_per_month = FloatField('Planned Amount'\
                               ,validators=[DataRequired()])
    date_period = DateField('Planned Month', format='%Y-%m-%d')
    comments = TextAreaField('Comments (optional)')
    submit = SubmitField('Post')

ActualPost型号 我有一个名为 actual_amount_name 的专栏我想通过使用查询 name 的 WTForm QuerySelectField 来填充其中的数据在Post型号:

class PostActualForm(FlaskForm):
    title = HiddenField('Please enter the Actual Amount details below:', default='actual')
    category = SelectField('Category', choices=[('savings', 'Savings')\
               ,('income', 'Income'), ('expenses', 'Expense')]\
               ,validators=[DataRequired()])
    actual_amount_name = QuerySelectField('Name', query_factory=db_query\
                         ,allow_blank=False, get_label='name')
    actual_amount = FloatField('Actual Amount', validators=[DataRequired()])
    date_posted = DateField('Date of actual amount', format='%Y-%m-%d')
    comments = TextAreaField('Comments (optional)')
    submit = SubmitField('Post')

这是经过 name 的路线从一个模型到另一个模型的数据:

@posts.route("/post/new_actual", methods=['GET', 'POST'])
@login_required
def new_actual_post():
    form = PostActualForm()
    if form.validate_on_submit():
        actualpost = ActualPost(title=form.title.data\ 
                    ,category=form.category.data\
                    ,actual_amount_name=request.form['actual_amount_name']\
                    ,actual_amount=form.actual_amount.data\ 
                    ,date_posted=form.date_posted.data\
                    ,comments=form.comments.data\
                    ,actual_author=current_user)
        db.session.add(actualpost)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('main.actual'))
    return render_template('create_actual_post.html', title='Actual',
                           form=form, legend='New Actual Amount')

我遇到的问题是,而不是 name正在转移:

name that I want transferred over

我认为字典键正在传输中,我看到一个数字:

what I actually got

我已经与这个问题斗争了 3 天,我相当确定 QuerySelectField 是罪魁祸首。

我尝试过其他调用表单的方法,比如 actual_amount_name=request.actual_amount_name.data哪些错误与

sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object>

我还尝试了多种其他方式,包括 get , from this documentation .我也尝试过查询数据库并使用 SelectField 而不是 QuerySelectField,但直到现在才成功。

我正在使用最新版本的 Python、Flask、SQLAlchemy 等,我正在使用 Pycharm 作为 IDE

编辑:

根据下面收到的评论(谢谢大家!)我查看了来自 this question 的答案

我已经删除了 .all()来自函数 query_db在我的模型中(也在上面编辑过)

重试,使用actual_amount_name=request.form['actual_amount_name']在 route ,我得到了相同的结果(字典键而不是名称)

将路由修改为actual_amount_name=form.actual_amount_name.data我添加了一些代码来将路由的输出写入 txt 文件:

actualpost = ActualPost(title=form.title.data, category=form.category.data\
                , actual_amount_name=form.actual_amount_name.data\
                , actual_amount=form.actual_amount.data, date_posted=form.date_posted.data\
                , comments=form.comments.data, actual_author=current_user)
    text = open("C:/Users/Ato/Desktop/Proiect Buget/actual_post_test_1.txt", "a")
    text.write(str(actualpost))
    text.close()
    db.session.add(actualpost)
    db.session.commit()

写入 txt 文件的数据包含正确的 actual_amount_name (惊吓 - 我的猫的名字):

ActualPost('actual, 'expenses' , 'Post('planned, 'expenses' , 'Spook', '123.0' , '2018-05-22 00:00:00', '')', '26.5' , '2018-05-22', 'testul 19')

但是我得到了调试器错误:

sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object>

最佳答案

我明白了!!!!

在进一步了解 StackOverflow 时,我偶然发现了 over this question以及用户 ACV 提供给它的答案。

因此,我需要做的就是在我的 route ,在 actual_amount_name=form.actual_amount_name.data 的末尾添加 .name,如下所示:

actual_amount_name=form.actual_amount_name.data.name

这是我的网页表格现在的样子:

enter image description here

这是文本文件中的输出:

ActualPost('actual, 'expenses' , 'Spook', '26.5' , '2018-05-22', 'God dammit' aaaargh#&*^$lkjsdfho')

关于Python QuerySelectField 和 request.form 返回字典键,而不是字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50472831/

相关文章:

java - 如何在我的 Android 应用程序中使用 onItemClick?

database - Qt 对 SQLite 的存储查询更快吗?

python - 使用棉花糖序列化 sqlalchemy hybrid_property

python - 在 Python 中使用 SQLAlchemy 连接到 Azure 数据库

python - 如何获取包含在其他两个列表中的元素的列表?

android - 在 Android 中从 uri 查询时无法从光标窗口读取 row 0, col -1

python - Flask 中的应用程序范围变量?

python - flask /Facebook : Flask-Oauth OAuthException: Missing redirect_uri parameter?

python - 从我的项目中的不同路径导入字典

python - AWS Lambda python 库函数错误