I'm using Flask with Wtforms (and Flask-WTF) to create forms for model CRUD. I've run into a question I've not been able to figure out today, mainly:
Given the following constants definitions:
ADMIN = 0
STAFF = 1
USER = 2
ROLE = {
ADMIN: 'admin',
STAFF: 'staff',
USER: 'user'}
and given the following model:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(80))
last_name = db.Column(db.String(80))
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(160))
role = db.Column(db.SmallInteger, default=USER.USER)
status = db.Column(db.SmallInteger, default=USER.NEW)
and given the following form generation code:
UserEdit = model_form(models.User, base_class=Form, exclude=['password'])
Can anyone suggest a modification to the form generation that would represent role
(a SmallInteger field) as a select field?
Better try use db.Enum
for role. But you also can set up own widget for your field:
from wtforms.widgets import Select
class ChoicesSelect(Select):
def __init__(self, multiple=False, choices=()):
self.choices = choices
super(ChoicesSelect, self).__init__(multiple)
def __call__(self, field, **kwargs):
field.iter_choices = lambda: ((val, label, val == field.default)
for val, label in self.choices)
return super(ChoicesSelect, self).__call__(field, **kwargs)
UserEdit = model_form(User, exclude=['password'], field_args={
'role': {
'widget': ChoicesSelect(choices=ROLE.items()),
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With