How to configure the display of the fields of the model model WTForm?

I use Flask with Wtforms (and Flask-WTF) to create forms for the CRUD model. I came across a question that I could not find out today, mainly:

Given the following definition of constants:

ADMIN = 0 STAFF = 1 USER = 2 ROLE = { ADMIN: 'admin', STAFF: 'staff', USER: 'user'} 

and the following model is given:

 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 the following form generation code is set:

 UserEdit = model_form(models.User, base_class=Form, exclude=['password']) 

Can anyone suggest a modification to the generation of the form, which will represent the role (SmallInteger field) as a selection field?

+4
source share
1 answer

Better try using db.Enum for the role. But you can also customize your 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()), } }) 
+7
source

Source: https://habr.com/ru/post/1490185/


All Articles