TypeError:必须使用User实例作为第一个参数调用未绑定方法make_valid_name()(改为使用unicode实例)

时间:2016-04-03 01:24:21

标签: python-2.7 flask sqlalchemy flask-sqlalchemy

我正在迁移我的旧代码 烧瓶sqlalchemy

from flask.ext.sqlalchemy import SQLAlchemy

要 sqlalchemy.orm - 会话制作者

from sqlalchemy.orm import sessionmaker

模型

@staticmethod
class User(Base):
    __tablename__ = 'user'
    id          = Column(Integer        , primary_key=True)
    name        = Column(String(20)     , unique=True, nullable=False)
.
.
.
    def make_valid_name(name):
        return re.sub('[^a-zA-Z0-9_\.]', '', name)

表格

def validate(self):
.
.
.    
if self.name.data != User.make_valid_name(self.name.data):
                self.name.errors.append('Please use letters, numbers, dots and underscores only.')
                return False

调用方法self.validate()时会抛出以下错误

TypeError: unbound method make_valid_name() must be called with User instance as first argument (got unicode instance instead)

我不确定需要修改什么,如何验证“self.name.data”来自字段数据

对此的任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

该错误意味着User.make_valid_name是一个实例方法,而不是您期望的静态方法。如果您想保留现有用途,解决方案是使用staticmethod来装饰方法,而不是类:

class User(Base):
    ...
    @staticmethod
    def make_valid_name(name):
        return ...

或者,您可以改为classmethod

class User(Base):
    ...
    @classmethod
    def make_valid_name(cls, name):
        return ...

答案 1 :(得分:0)

只有选项是再次创建User对象并初始化属性,然后将其作为参数而不是直接传递给表单对象名称

user = User(
name = self.name.data
)

if self.name.data != User.make_valid_name(user):

并在模型中访问

user.name

:@必须重写所有内容。

任何其他最佳解决方案也将受到赞赏。如果其他人将来面临类似的问题。