如何设置表单元素名称?

时间:2016-03-22 21:28:58

标签: python flask flask-sqlalchemy wtforms flask-wtforms

我有一个用Flask编写的Web应用程序,它使用WTForms,SQLAlchemy和相应的Flask扩展,Flask-SQLAlchemy,Flask-WTF和WTForms-Alchemy。

对于以下型号:

class User(db.Model, UserMixin):
    """
    Represents a registered user.

    @TODO Override setter for password so it is always encrypted.
    @TODO Add last_login column
    """

    __tablename__ = 'User'

    def __init__(self, username=None, password=None, email=None):
        self.username = username
        self.email = email
        self.password = encrypt(password)

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, default=u'Anonymous Lifter')
    username = db.Column(db.String, nullable=False)
    password = db.Column(db.String, nullable=False)

我尝试按以下方式创建表单:

class LoginForm(ModelForm):
    """ Form used to login a user that does not use social login. """
    class Meta:
        model = User
        only = [u'username', u'password']
        field_args = {u'password': {'widget': PasswordInput()}}
    remember_me = BooleanField(u'Remember me')

我的问题是,当我在页面上显示表单时,usernamepassword似乎都是低级的。如何将其标签(?)/名称(?)设置为大写?

1 个答案:

答案 0 :(得分:2)

在模型中定义列时使用info属性。例如:

class User(db.Model, UserMixin):
    """
    Represents a registered user.

    @TODO Override setter for password so it is always encrypted.
    @TODO Add last_login column
    """

    __tablename__ = 'User'

    def __init__(self, username=None, password=None, email=None):
        self.username = username
        self.email = email
        self.password = encrypt(password)

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, default=u'Anonymous Lifter', info={'label': 'Name'})
    username = db.Column(db.String, nullable=False, info={'label': 'Username'})
    password = db.Column(db.String, nullable=False, info={'label': 'Password'})

或者在定义表单时使用field_args:

class LoginForm(ModelForm):
    """ Form used to login a user that does not use social login. """
    class Meta:
        model = User
        only = [u'username', u'password']
        field_args = {
            u'password': {
            'widget': PasswordInput(),
            'label': 'PASSWORD'
            },
            u'username': {'label': 'USERNAME'},
        }
    remember_me = BooleanField(u'Remember me')