Don't add the form field values to the session; SQLAlchemy has no idea what object you are trying to add here.
Instead, create a new Contact
object and add that to the session:
if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
else:
contact = Contact(form.data['surname'], form.data['firstname'],
form.data['email'], form.data['mobile'],
form.data['work_location'])
db.session.add(contact)
db.session.commit()
flash("Contact added successfully.")
return redirect(url_for("contact_list"))
You could also remove the __init__
method from your Contact
model entirely (SQLAlchemy creates one for you anyway, using keyword arguments instead of required positional arguments):
class Contact(db.Model):
id = db.Column(db.Integer, primary_key = True)
surname = db.Column(db.String(100))
firstname = db.Column(db.String(100))
email = db.Column(db.String(100))
mobile = db.Column(db.String(20))
work_location = db.Column(db.String(100))
#user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Contact %r>' % (self.surname)
and use the Form.populate_obj()
function to save yourself having to type out all those fields.
if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
else:
contact = Contact()
form.populate_obj(contact)
db.session.add(contact)
db.session.commit()
flash("Contact added successfully.")
return redirect(url_for("contact_list"))
or even:
else:
contact = Contact(**form.data)
db.session.add(contact)