Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python QuerySelectField and request.form returning dict key, not dict value

I am not a programmer yet (working on it - this is my first big project), so sorry for the messy-ugly code.

I have some issues using QuerySelectField and request.form['form_field_name'] to pull data from a SQlite table and to put it in another table.

I am trying to get data from the name column in the Post model to fill the actual_amount_name column in the ActualPost model, but I think I am actually pulling dictionary keys.

These are the 2 models/tables I am using:

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}')"

Now the forms:

In the Post model I have a column called name. The data in this filed is added by the user using WTForms (the name field in the class below):

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

In the ActualPost model I have a column called actual_amount_name and I want to fill the data in it by using a WTForm QuerySelectField, which queries the name in the 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')

This is the route that takes the passes the name data from one model to the other:

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

The issue I have, is that instead of the name being transferred over:

name that I want transferred over

I think that the dictionary key is being transferred and I see a number:

what I actually got

I have been battling this for 3 days and I am fairly certain that QuerySelectField is the culprit.

I have tried other ways of calling the form, like actual_amount_name=request.actual_amount_name.data which errors-out with

sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object>

I have also tried multiple other ways, including get, from this documentation. I have also tried to query the database and to use the SelectField, instead of QuerySelectField, but no luck until now.

I am using the latest versions of Python, Flask, SQLAlchemy, etc, and I am using Pycharm as an IDE

Edit:

Based on the comments received below (thank you all!) I went over the answers from this question

I have removed .all() from the function query_db in my models (edited above as well)

Retried, using actual_amount_name=request.form['actual_amount_name'] in the route and I got the same result (dict key instead of name)

Modified the route to actual_amount_name=form.actual_amount_name.data and I added a bit of code to write the output of the route to a txt file:

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()

The data being written to the txt file contains the correct actual_amount_name (Spook - my cat's name):

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

But I get the debugger error:

sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object>

like image 622
derzemel Avatar asked Mar 28 '26 13:03

derzemel


1 Answers

I got it!!!!

while poking some more around StackOverflow, I stumbled over this question and the answer provided to it by the user ACV.

So, all I needed to do was, in my route, to add .name at the end of actual_amount_name=form.actual_amount_name.data, like so:

actual_amount_name=form.actual_amount_name.data.name

This is what my web page table looks like now:

enter image description here

And this is the output in the text file:

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

like image 67
derzemel Avatar answered Mar 30 '26 03:03

derzemel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!