Ursa Major Ursa Major - 6 months ago 38
Python Question

TutorialsPoint - Flask – SQLAlchemy not working

I did all that was stated on tutorial point (just copied and pasted), but when I tried to add a student entry,i.e. ‘Add Student’ it gives

Bad Request
The browser (or proxy) sent a request that this server could not understand.

Please advise if there is anything wrong with the tutorial.

Anything wrong with this:

<!DOCTYPE html>

<h3>Students - Flask SQLAlchemy example</h3>

{%- for category, message in get_flashed_messages(with_categories = true) %}
<div class = "alert alert-danger">
{{ message }}
{%- endfor %}

<form action = "{{ request.path }}" method = "post">
<label for = "name">Name</label><br>
<input type = "text" name = "name" placeholder = "Name" /><br>
<label for = "email">City</label><br>
<input type = "text" name = "city" placeholder = "city" /><br>
<label for = "addr">addr</label><br>
<textarea name = "addr" placeholder = "addr"></textarea><br>
<label for = "PIN">City</label><br>
<input type = "text" name = "pin" placeholder = "pin" /><br>
<input type = "submit" value = "Submit" />


Ref: http://www.tutorialspoint.com/flask/flask_sqlalchemy.htm


The tutorial has an indentation problem in the student class. The constructor code should be indented one level so it becomes a method of the student class.

Corrected code: (note the indent of "def init(self, name, city, addr,pin):" and the code below)

class students(db.Model):
   id = db.Column('student_id', db.Integer, primary_key = True)
   name = db.Column(db.String(100))
   city = db.Column(db.String(50))
   addr = db.Column(db.String(200)) 
   pin = db.Column(db.String(10))

   def __init__(self, name, city, addr,pin):
      self.name = name
      self.city = city
      self.addr = addr
      self.pin = pin

The reason is, if that indent is not there, python will not see this function as a constructor of the student class. So the constructor with the matching number of arguments is not found, resulting in the error.