flask-admin ModelView自定义create_form

时间:2014-04-24 03:52:19

标签: flask flask-wtforms flask-admin

我在flask-admin中创建了一个自定义UserViewCreateForm(使用wtforms),如下所示: -

from app.vendors.models import Vendor

class UserViewCreateForm(form.Form):
    username = fields.TextField('Username')
    first_name = fields.TextField('First Name')
    last_name = fields.TextField('Last Name')
    email = fields.TextField('Email')
    contact_number = fields.TextField('Contact Number')
    password = fields.PasswordField('Password')
    is_admin = fields.BooleanField('Is Admin')
    is_active = fields.BooleanField('Is Active')
    is_verified = fields.BooleanField('Is Verified')
    vendor = fields.SelectField('Vendor', coerce=int)


class UserView(ModelView):
    form_overrides = dict(title=SelectField)
    form_args = dict(
        # Pass the choices to the `SelectField`
        title=dict(
            choices=TITLE_TYPE
        ))

    def __init__(self, session, **kwargs):
        super(UserView, self).__init__(User, session, **kwargs)

    def is_accessible(self):
        return login.current_user.is_authenticated()

    def create_form(self):
        form = UserViewCreateForm()
        form.vendor.choices = [(0, '')] + [(v.id, v.name) for v in Vendor.query.all()]
        return form

供应商选择字段给我Not a valid choice验证错误。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

可能是因为你没有选择?

CA_STATES = [
    ('', 'Province'),
    ('AB', 'Alberta'),
    ('BC', 'British Columbia'),
    ('MB', 'Manitoba'),
    ('NB', 'New Brunswick'),
    ('NL', 'Newfoundland and Labrador'),
    ('NS', 'Nova Scotia'),
    ('ON', 'Ontario'),
    ('PE', 'Prince Edward Island'),
    ('QC', 'Quebec'),
    ('SK', 'Saskatchewan'),
    ('NT', 'Northwest Territories'),
    ('NU', 'Nunavut'),
    ('YT', 'Yukon'),
]

state_ca = SelectField('Province', choices=CA_STATES)

答案 1 :(得分:0)

如果您想从供应商表中提取您的选择,那么您需要来自wtforms.ext.sqlalchemy的QuerySelectField(在WTForms 3.0之前 - 在3.0之后,它现在是一个单独的WTForms-SQLAlchemy包。)< / p>

from app.vendors.models import Vendor
from wtforms.ext.sqlalchemy import QuerySelectField

class UserViewCreateForm(form.Form):
    username = fields.TextField('Username')
    first_name = fields.TextField('First Name')
    last_name = fields.TextField('Last Name')
    email = fields.TextField('Email')
    contact_number = fields.TextField('Contact Number')
    password = fields.PasswordField('Password')
    is_admin = fields.BooleanField('Is Admin')
    is_active = fields.BooleanField('Is Active')
    is_verified = fields.BooleanField('Is Verified')
    vendor = QuerySelectField('Vendor')

class UserView(ModelView):

    def create_form(self):
        form = UserViewCreateForm()
        form.vendor.query = Vendor.query.all()
        return form