Keon Kim
Keon Kim

Reputation: 760

flask-sqlalchemy stores unintended variables into database

I am building a simple Q&A (interview and answer) with flask. The relevant code is the following:

@blueprint.route("/interview/", methods=['GET', 'POST'])
def interview():
    rows = Question.query.count()  #counts number of rows 
    r = random.randint(1,rows)     #picks a number from 1 to 'rows'
    question=Question.query.get(r) #queries the index generated by randint

    user=User.query.get(session['user_id']) #gets session data
    created_at=''
    form = InterviewForm()
    if form.validate_on_submit():
        new_answer = Answer.create(text=form.answer.data, user=user, question=question, created_at=created_at) #basically a method that combines db.session.add and db.session.commit
        flash("Your answer has been submitted")
        return redirect(url_for('interview.list', question=question.id))
    return render_template("interview/interview.html", form=form, question=question)

The intended result is:

  1. User sees a generated random question
  2. answers to the question and POSTs to server
  3. insert the answer to database with corresponding question id (one-to-many relationship)

However, the what I get is:

I think something is wrong with generating random number, that it generates different random integer for viewing and inserting.

Upvotes: 1

Views: 62

Answers (1)

Alex Lisovoy
Alex Lisovoy

Reputation: 6065

You should in some way retrieve question_id and use it when you try save answer. For example, you can add hidden field to form which should store question id. In your view you should get question object using provided question_id from form(post data).

Another way, you can add question_id to your url schema, like this:

@blueprint.route("/interview/", methods=['GET'])
@blueprint.route("/interview/<int:question_id>", methods=['POST'])
def interview(question_id=None):
    ...
    question=Question.query.get(question_id)
    ...

Upvotes: 1

Related Questions