用WTForms StringField写入Postgres的编程错误

时间:2018-02-16 03:02:48

标签: postgresql flask wtforms flask-wtforms

我的数据库是Postgres实例。 我的模型定义为:

from app import db
class Device(db.Model):
    __tablename__ = 'device'

    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String())

我的定义为:

from flask_wtf import FlaskForm
from wtforms import StringField

class EditDevices(FlaskForm):
    device_name = StringField("Device Name", validators=[])
    submit = SubmitField['Submit']

我在表单中收到错误:

    sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'StringField' [SQL: 'UPDATE device SET name=%(name)s WHERE device.id = %(device_id)s'] [parameters: {'name':  <wtforms.fields.core.StringField object at 0x110580c18>, 'device_id': 208}]

我出错的任何想法?

2 个答案:

答案 0 :(得分:3)

您的代码不完整 - 您未显示实际尝试设置模型数据的位置并将其保存到数据库,但错误显示<wtforms.fields.core.StringField object at 0x110580c18>是您设置的值到name属性,所以您可能会这样做:

device = Device()
device.name = form.device_name
db.session.add(device)
db.session.commit()

这会导致类似于您所看到的错误,因为form.device_nameStringField,而您需要用户提交的数据。要从表单元素获取数据,您需要使用.data属性:

device = Device()
device.name = form.device_name.data
db.session.add(device)
db.session.commit()

答案 1 :(得分:0)

使用email.data数据位置

class RegisterForm(FlaskForm):
    email = StringField("Email", validators=[DataRequired(), Email()])
    password = PasswordField("Password", validators=[DataRequired(),Length(min=6,max=15)])
    password_confirm = PasswordField("Confirm Password", validators=[DataRequired(),Length(min=6,max=15), EqualTo('password')])
    first_name = StringField("First Name", validators=[DataRequired(),Length(min=2,max=55)])
    last_name = StringField("Last Name", validators=[DataRequired(),Length(min=2,max=55)])
    submit = SubmitField("Register Now")

    def validate_email(self,email):
        user = User.query.filter_by(email=**email.data**).first()
        if user:
            raise ValidationError("Email is already in use. Pick another one.")