SQLAlchemy错误 - TypeError:add_all()只需要2个参数(给定6个)

时间:2014-02-11 11:23:26

标签: python sqlalchemy flask flask-wtforms

我在下面收到此错误,有人可以帮忙吗?如果这还不够,请告诉我。我有一个forms.py,addcontact模板,以下来自app.py。

反馈错误:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
   reraise(exc_type, exc_value, tb)
 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
   response = self.full_dispatch_request()
 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
   rv = self.handle_user_exception(e)
 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
   reraise(exc_type, exc_value, tb)
 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
   rv = self.dispatch_request()
 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
   return self.view_functions[rule.endpoint](**req.view_args)
 File "/home/rob/webappan2/addressbook/app.py", line 63, in contact_add
,[request.form['mobile']],[request.form['work_location']])
 File "/usr/share/pyshared/sqlalchemy/orm/scoping.py", line 113, in do
   return getattr(self.registry(), name)(*args, **kwargs)
TypeError: add_all() takes exactly 2 arguments (6 given)

我的方法

@app.route('/addcontact/', methods=['GET','POST'])
def contact_add():
    form = ContactsForm()
    if request.method == 'POST':
        if form.validate() == False:
            flash('All fields are required.')
        else:
            db.session.add_all(request.form['surname'],request.form['firstname'],request.form['email']\
                        ,request.form['mobile'],request.form['work_location'])
            db.session.commit()
            flash("Contact added successfully.")
            return redirect(url_for("contact_list"))
    elif request.method == 'GET':
        return render_template('addcontact.html', title = 'Add Contact',form = form)

这是我的联系模式:

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 __init__(self,surname,firstname,email,mobile,work_location):
        self.surname =  surname
        self.firstname = firstname
        self.email = email
        self.mobile = mobile
        self.work_location = work_location

    def __repr__(self):
        return '<Post %r>' % (self.surname)

这是我的联系表格:

class ContactsForm(Form):
    surname = fields.TextField(validators=[validators.required()])
    firstname = fields.TextField(validators=[validators.required()])
    email = fields.TextField(validators=[validators.required()])
    mobile = fields.TextField(validators=[validators.required()])
    work_location = fields.TextField(validators=[validators.required()])

1 个答案:

答案 0 :(得分:4)

不要将表单字段值添加到会话中; SQLAlchemy 不知道你想在这里添加什么对象。

相反,创建一个新的Contact对象并将 添加到会话中:

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"))

您也可以完全从__init__模型中删除Contact方法(无论如何,SQLAlchemy都会为您创建一个方法,使用关键字参数而不是必需的位置参数):

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)

并使用Form.populate_obj() function来保存自己必须输入所有这些字段。

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"))

甚至:

    else:
        contact = Contact(**form.data)
        db.session.add(contact)