Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to customize WTForm model_form field mapping?

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?

like image 321
One Bad Panda Avatar asked Mar 23 '23 06:03

One Bad Panda


1 Answers

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()),
    }
})
like image 59
tbicr Avatar answered Apr 25 '23 06:04

tbicr