烧瓶。 sqlalchemy.exc.InterfaceError:<app.models.menu object =“”at =“”0x7f287026dd10 =“”> </app.models.menu>

时间:2014-07-14 08:57:58

标签: flask sqlalchemy wtforms

我在forms.py中使用 QuerySelectField ,在提交时我收到以下错误:

InterfaceError: (InterfaceError) Error binding parameter 8 - probably unsupported 
type. u'INSERT INTO menu (title, title_eng, alias, menu_type, ordering, 
check_out_time, access, published, parent_id, image, content, content_eng, 
metades, metakey) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
(u'\u0423\u0441\u043b\u043e\u0432\u0438\u044f \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u044f',
u'terms of connecting', u'terms', u'simple', 4, '2014-01-23 00:00:00.000000',
u'public', u'1', <app.models.Menu object at 0x7fe158171990>, u'url/folder/image.jpg', 
u'asd', u'asd', u'asd', u'asd')

我用Google搜索并发现问题是 QuerySelectField 的返回值是对象,我必须将其转换为字符串,但我无法解决。你能帮我解决这个问题吗?

这是我的forms.py:

def menu_list():
    return Menu.query

class Add_menu_form(Form):
    """Add_menu_form is used to add/edit menu"""
    title = TextField(u'Название меню', [validators.Length(min=1, max=250), validators.Required()])
    title_eng = TextField(u'Название меню на английском', [validators.Length(min=1, max=250), validators.Required()])
    alias = TextField(u'Короткое название')
    menu_type = SelectField(u'Тип меню', 
                choices=[('simple', u'обычное'),
                        ('blog', u'блог'),
                        ('products', u'продукция'),
                        ('gallery', u'галерея')])
    ordering = IntegerField(u'Позиция')
    check_out_time = DateField(u'Дата публикации')
    access = SelectField(u'Доступ', 
                choices=[('public', u'открытый'),
                        ('registered', u'для зарегистрированных'),
                        ('admin', u'для администратора')])
    published = SelectField(u'Опубликовать', 
                choices=[('1', u'да'),
                        ('0', u'нет')])
    parent_id = QuerySelectField(u'Родительская группа',
                            query_factory = menu_list,
                            get_pk = lambda a: a.id,
                            get_label = lambda a: a.title,
                            allow_blank=True)
    image = TextField(u'Заглавная картинка')
    content = TextAreaField(u'Содержание', [validators.Required()])
    content_eng = TextAreaField(u'Содержание на английском', [validators.Required()] )
    metades = TextAreaField(u'HTML описание')
    metakey = TextAreaField(u'HTML ключевые слова')

这是我的models.py:

class Menu(db.Model):
    """Menu is used for websites navigation titles.
    eg. Home/About Us/Blog/Contacts/and etc""" 

    id          = db.Column(db.Integer, primary_key = True)
    title       = db.Column(db.String(255))
    title_eng   = db.Column(db.String(255))
    alias       = db.Column(db.String(255))
    menu_type   = db.Column(db.String(10))
    #menu type: simple, blog, gallery, contacts, products
    ordering    = db.Column(db.SmallInteger, default = '1')
    check_out_time = db.Column(db.DateTime)
    access      = db.Column(db.String(30))
    #access: user, reductor, manager, administrator 
    published   = db.Column(db.SmallInteger, default = '1')
    parent_id   = db.Column(db.Integer)
    image       = db.Column(db.String(350))
    content     = db.Column(db.String)
    content_eng = db.Column(db.String)
    metades     = db.Column(db.String(350))
    metakey     = db.Column(db.String(350))

    def __init__(self, title, title_eng, alias, 
            menu_type, ordering, check_out_time, access,
            published, parent_id, image, content, content_eng,
            metades, metakey):
        self.title = title
        self.title_eng = title_eng
        self.alias = alias
        self.menu_type = menu_type
        self.ordering = ordering
        self.check_out_time = check_out_time
        self.access = access
        self.published = published
        self.parent_id = parent_id
        self.image = image
        self.content = content
        self.content_eng = content_eng
        self.metades = metades
        self.metakey = metakey

    # __str__ is a special method, like __init__, that is 
    # supposed to return a string representation of an object.
    def __str__(self):
        return '%.d' % (self.id)

和views.py:

@admin.route('/manage/add_menu', methods = ['GET', 'POST'])
@login_required
def add_menu(parent = ''):
    form = Add_menu_form()

    if form.validate_on_submit():
        new_menu = Menu(
            form.title.data,
            form.title_eng.data,
            form.alias.data,
            form.menu_type.data,
            form.ordering.data,
            form.check_out_time.data,
            form.access.data,
            form.published.data,
            form.parent_id.data,
            form.image.data,
            form.content.data,
            form.content_eng.data,
            form.metades.data,
            form.metakey.data)
        form.populate_obj(new_menu)
        db.session.add(new_menu)
        db.session.commit()

        flash('New menu was added successfully.')   
        return redirect(url_for('cabinet.manage', current = 'menu_settings'))
    return render_template('admin/manage/site_figuration/add_menu.html',
        title = 'Internet market',
        parent = parent,
        form = form)

1 个答案:

答案 0 :(得分:2)

最后,该问题在经过数小时的谷歌搜索后得以解决。问题是关于QuerySelectField。问题是,当检索form.parent_id.data时,它实际上返回了一个查询对象,我需要一个字符串vaue。所以我将值转换为字符串并添加提交给数据库:

a = str(form.parent_id.data)

if form.validate_on_submit():
        new_menu = Menu(
            form.title.data,
            form.title_eng.data,
            form.alias.data,
            form.menu_type.data,
            form.ordering.data,
            form.check_out_time.data,
            form.access.data,
            form.published.data,
            a, #form.parent_id.data,
            form.image.data,
            form.content.data,
            form.content_eng.data,
            form.metades.data,
            form.metakey.data)
        form.populate_obj(new_menu)
        db.session.add(new_menu)
        db.session.commit()