Flask. sqlalchemy.exc.InterfaceError: <app.models.Menu object at 0x7f287026dd10>

馋奶兔 提交于 2019-12-02 14:08:37

问题


I am using QuerySelectField in my forms.py and when submitting it I get the following error:

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

I googled it and found out that the issue is that the returned value of QuerySelectField is object and I have to convert it to string, but I couldnt. Can you please help me with that issue?

here is my 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 ключевые слова')

this is my 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)

and the 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:


Finally the issue is solved after hours of googling. the issue was about QuerySelectField. The problems was that when retrieving form.parent_id.data it actually returned a query object, whie I need a string vaue. So I converted the value to string and added submitted it to database:

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


来源:https://stackoverflow.com/questions/24732871/flask-sqlalchemy-exc-interfaceerror-app-models-menu-object-at-0x7f287026dd10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!