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

时间:2018-05-22 16:51:17

标签: python sqlite flask sqlalchemy wtforms

我还不是程序员(正在研究它 - 这是我的第一个大项目),对于那些乱糟糟的代码感到抱歉。

我在使用QuerySelectFieldrequest.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的列,我希望使用WTForm QuerySelectField填充其中的数据,该查询name Post } model:

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>

我还尝试了多种其他方式,包括getfrom this documentation。我也尝试查询数据库并使用SelectField而不是QuerySelectField,但直到现在都没有运气。

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

修改

根据以下收到的评论(谢谢大家!)我从this question

回答了答案

我已从模型中的.all()函数中移除query_db(上面也已编辑过)

在路线中使用actual_amount_name=request.form['actual_amount_name']重新尝试,我得到了相同的结果(dict键而不是名字)

修改了到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(Spook - 我的猫的名字):

  

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>

1 个答案:

答案 0 :(得分:0)

我明白了!!!!

在围绕StackOverflow进行更多搜索时,我偶然发现over this question并且用户ACV提供了答案。

所以,在我的路线中,我需要做的就是在.name的末尾添加actual_amount_name=form.actual_amount_name.data,如下所示:

  

<强> 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')

相关问题