0

I want to pass the selected {{ exam[0] }} to the show_exam_form function. However I could not do that.

Environment

Python 3.6.1
Flask==0.12.2
Jinja2==2.9.6

app.py

@app.route('/exam/<int:exam_id>', methods=['POST'])
def show_exam_form(exam_id):
    print(exam_id)

html

<form action="{{ url_for('show_exam_form', exam_id=exam_id) }}" method='POST'>
  <select name=exam_id>
    {% for exam in exams %}
    <option value="{{exam[0]}}">{{exam[1]}}</option>
    {% endfor %}
  </select>

How can I solve it?
Please let me know if you need more information to solve it.
Thank you!!!

tekun
  • 71
  • 4
  • 14

2 Answers2

2

Requesting the id as parameter is not necessary. Here is an example how to handle this selected value for future OPs.

In app.py:

@app.route('/exam', methods=['GET','POST'])
def show_exam_form():
    exams = {
        "IT-101":"IT Fundamentals",
        "IT-201": "Object Oriented Programming",
        "IT-301": "Database Management",
        "IT-401": "Operating Systems"
    }
    if request.method == "GET":
        return render_template('so.html', exams = exams)
    else:
        exam_id = request.form["exam_id"]
        flash(exam_id)
        return render_template('so.html', exams = exams)

In so.html template (in my case it extends a base templete):

{% extends "layout.html" %}
{% block content %}
    <form action="{{ url_for('show_exam_form') }}" class="form" method='POST'>
        <div class="form-group">
            <select name="exam_id" class="form-control">
                {% for key,value in exams.items() %}
                    <option value="{{ key }}">{{ value }}</option>
                {% endfor %}
            </select>
        </div>
        <input type="submit" class="btn btn-primary" value="Submit">
    </form>
{% endblock %}

Output:

Input Form Figure 1: Input Form

enter image description here Figure 2: Flashing the selected value

arshovon
  • 13,270
  • 9
  • 51
  • 69
  • 1
    Yeah! I noticed that it is not necessary after post. But you give me the great example. Thank you!!! – tekun Oct 01 '17 at 05:48
0

I do not need to send the exam_id from jinja to Flask.
Just send via POST and get it with request.form['exam_id'] in the show_exam_form function.

tekun
  • 71
  • 4
  • 14