0

I am a beginner to Python web development. I was practicing UPDATE operation. Problem is occurring when I am try to fetch a value from text box and store it in a variable in python. The code I've written I am showing below:

mysql> desc sample;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| ID    | int(11)     | NO   | PRI | NULL    | auto_increment |
| NAME  | varchar(30) | YES  |     | NULL    |                |
| EMAIL | varchar(70) | YES  |     | NULL    |                |
| PHONE | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

This is my database

{% for col in students %}
<input type="hidden" class="form-control" name="id" placeholder="Id" value="{{col.0}}" />
<input type="text" class="form-control" id="n" name="name" placeholder="Name" value="{{col.1}}" />
<input type="email" class="form-control" id="e" name="email" placeholder="Email" value="{{col.2}}" />
<input type="tel" pattern="[0-9]{10}" class="form-control" name="phone" id="p" placeholder="Phone" value="{{col.3}}" />
@app.route('/update', methods=['POST','GET'])
def update():
    if request.method == 'POST':

        id_val = request.method['id']
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']

        #Updating values
        cur = mysql.get_db().cursor()
        cur.execute('UPDATE sample SET name=%s, email=%s, phone=%s WHERE id=%s',(name,email,phone,id_val))
        flash("Data Updated Successfully !!")
        mysql.get_db().commit()
        return redirect(url_for('home'))

This is my Python code. The problem is occuring id_val = request.method['id'] in this line. It's telling TypeError: string indices must be integers.

What is needed to be corrected here ? Please help me out

Barefaced Bear
  • 688
  • 1
  • 9
  • 30

1 Answers1

1

You are using

request.method['id']

which evaluates to 'POST'['id'].

request.method gives you 'POST' string and ['id'] tries to slice it using index.

As the 'id' is not an index, it is giving telling you this -

TypeError: string indices must be integers.

Try changing the request.method['id'] to request.form['id']. This should work.

Underoos
  • 4,708
  • 8
  • 42
  • 85