Sunday, 15 February 2015

python - WTForms dynamic forms with configurable validation -



python - WTForms dynamic forms with configurable validation -

i'm building scheme allows admin users add together "questions" database. each type of question has wtforms object associated it. display page, loop on questions , generate form consisting of form fields each question.

class textquestionform(form): value = textfield("value", validators=[]) class question(db.model): # sqlalchemy model using single table inheritance def field_name(self): homecoming "question_%s" % self.id class textquestion(question): form = textquestionform def get_form(page_id): questions = question.query.filter(question.page_id == page_id).all() class f(form): pass q in questions: setattr(f, q.field_name(), formfield(q.form)) homecoming f()

this works simple cases validation same given question type, need provide configurable validation options each instance of question, illustration imagine if question model extended:

class question(db.model): # ... other fields min_length = db.column(db.integer, nullable=true) max_length = db.column(db.integer, nullable=true)

what appropriate way wtforms length validator on value field within form field, given min/max lengths different (or missing) each question?

to have finish command on validation can create custom field inheriting textfield , redefine pre_validate method

def pre_validate(self, form=none)

and within function can checks want

http://wtforms.simplecodes.com/docs/0.6/fields.html#wtforms.fields.field.pre_validate

python flask wtforms flask-wtforms

No comments:

Post a Comment