Tutorialspoint - Flask – Sqlalchemy Not Working
Solution 1:
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):" in 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.
Solution 2:
It's not following the class naming convention. The student class should use Camel case. Try this:
student = Students(request.form['name'], request.form['city'],
request.form['addr'], request.form['pin'])
The SQLAlchemy model should also follow the same, Students not students.
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))
Edit Given Iron Fist's comment that the same code is running okay for him, its very likely that there is a mistake or typo in your code for creating a new student object. Even if you have copy pasted the code, an error may occur when typing the code assuming you did not use CTRL-V or when pasting it. According to the Flask docs:
What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.
Therefore if @IronFist ran the same code without a problem, but for you its returning a bad response error which as explained above is as a result of a missing key in the form, then its most likely a mistake on the code you are running. Also read this and this they are similar to your question.
Post a Comment for "Tutorialspoint - Flask – Sqlalchemy Not Working"