我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用wtforms.Form()。
def __init__(self, request=None, *args, meta=None, **kwargs): form_meta = meta_for_request(request) form_meta.update(meta or {}) kwargs['meta'] = form_meta self.request = request if request is not None: formdata = kwargs.pop('formdata', sentinel) if formdata is sentinel: if request.files: formdata = ChainRequestParameters( request.form, request.files) else: formdata = request.form # signature of wtforms.Form (formdata, obj, prefix, ...) args = chain([formdata], args) super().__init__(*args, **kwargs)
def _generateFormClasses(self, classes): ''' Loops over all ModelClasses and generates a new WTForm class. New form classes are named as [ModelClassName]Form. Sets the new form as an attribute on MarvinForm. Also populates the _param_to_form_lookup dictonary with all ModelClass/WTForm parameters and their corresponding forms. e.g. _param_form_lookup['name'] = marvin.tools.query.forms.IFUDesignForm ''' for key, val in classes.items(): classname = '{0}Form'.format(key) try: newclass = formClassFactory(classname, val, ModelForm) except Exception as e: warnings.warn('class {0} not Formable'.format(key), MarvinUserWarning) else: self.__setattr__(classname, newclass) self._loadParams(newclass)
def allowed_assignment(self, request: LocalProxy, form: Form) -> bool: """Return if assignment is allowed, per settings. :param request: The request context object. :param form: form to check """ lst = self.setting('assignments').value assignment = request.form['assignment'] category = request.form.get('category', None) if ':' in lst: datum = dict(l.split(':') for l in lst.splitlines()) lst = datum.get(category, '*') if lst == '*': return True if assignment not in str2lst(lst): prefix = 'Assignment' if category: prefix = 'For "%s" inquiries, assignment' % category form.errors.setdefault('assignment', []) \ .append( '%s "%s" is not allowed. Only the following ' 'assignments are: %s' % (prefix, assignment, lst)) return False return True
def build_file_select_form(schema): class FileSelectForm(Form): pass for field_name, field_schema in schema.items(): if field_schema['type'] == 'boolean': field = BooleanField() elif field_schema['type'] == 'string': if 'allowed' in field_schema: choices = [(c, c) for c in field_schema['allowed']] field = SelectField(choices=choices) else: field = StringField() elif field_schema['type'] == 'objectid': field = FileSelectField('file') else: raise ValueError('field type %s not supported' % field_schema['type']) setattr(FileSelectForm, field_name, field) return FileSelectForm
def __init__(self, *args, **kwargs): warnings.warn(FlaskWTFDeprecationWarning( '"flask_wtf.Form" has been renamed to "FlaskForm" ' 'and will be removed in 1.0.' ), stacklevel=3) super(Form, self).__init__(*args, **kwargs)
def model_form(model, base_class=Form, only=None, exclude=None, field_args=None, converter=None): """ Create a wtforms Form for a given Django model class:: from wtforms.ext.django.orm import model_form from myproject.myapp.models import User UserForm = model_form(User) :param model: A Django ORM model class :param base_class: Base form class to extend from. Must be a ``wtforms.Form`` subclass. :param only: An optional iterable with the property names that should be included in the form. Only these properties will have fields. :param exclude: An optional iterable with the property names that should be excluded from the form. All other properties will have fields. :param field_args: An optional dictionary of field names mapping to keyword arguments used to construct each field object. :param converter: A converter to generate the fields based on the model properties. If not set, ``ModelConverter`` is used. """ field_dict = model_fields(model, only, exclude, field_args, converter) return type(model._meta.object_name + 'Form', (base_class, ), field_dict)
def model_form(model, base_class=Form, only=None, exclude=None, field_args=None, converter=None): """ Creates and returns a dynamic ``wtforms.Form`` class for a given ``db.Model`` class. The form class can be used as it is or serve as a base for extended form classes, which can then mix non-model related fields, subforms with other model forms, among other possibilities. :param model: The ``db.Model`` class to generate a form for. :param base_class: Base form class to extend from. Must be a ``wtforms.Form`` subclass. :param only: An optional iterable with the property names that should be included in the form. Only these properties will have fields. :param exclude: An optional iterable with the property names that should be excluded from the form. All other properties will have fields. :param field_args: An optional dictionary of field names mapping to keyword arguments used to construct each field object. :param converter: A converter to generate the fields based on the model properties. If not set, ``ModelConverter`` is used. """ # Extract the fields from the model. field_dict = model_fields(model, only, exclude, field_args, converter) # Return a dynamically created form class, extending from base_class and # including the created fields as properties. return type(model.kind() + 'Form', (base_class,), field_dict)
def model_form(model, base_class=Form, only=None, exclude=None, field_args=None, converter=None): """ Creates and returns a dynamic ``wtforms.Form`` class for a given ``ndb.Model`` class. The form class can be used as it is or serve as a base for extended form classes, which can then mix non-model related fields, subforms with other model forms, among other possibilities. :param model: The ``ndb.Model`` class to generate a form for. :param base_class: Base form class to extend from. Must be a ``wtforms.Form`` subclass. :param only: An optional iterable with the property names that should be included in the form. Only these properties will have fields. :param exclude: An optional iterable with the property names that should be excluded from the form. All other properties will have fields. :param field_args: An optional dictionary of field names mapping to keyword arguments used to construct each field object. :param converter: A converter to generate the fields based on the model properties. If not set, ``ModelConverter`` is used. """ # Extract the fields from the model. field_dict = model_fields(model, only, exclude, field_args, converter) # Return a dynamically created form class, extending from base_class and # including the created fields as properties. return type(model._get_kind() + 'Form', (base_class,), field_dict)
def get_name_form(block_json, error_messages): class NameForm(Form): pass for question in SchemaHelper.get_questions_for_block(block_json): for answer in question['answers']: guidance = answer.get('guidance', '') label = answer.get('label') or question.get('title') field = get_string_field(answer, label, guidance, error_messages) setattr(NameForm, answer['id'], field) return NameForm
def get_date_form(answer=None, error_messages=None): """ Returns a date form metaclass with appropriate validators. Used in both date and date range form creation. :param error_messages: The messages during validation :param answer: The answer on which to base this form :return: The generated DateForm metaclass """ class DateForm(Form): day = StringField() year = StringField() validate_with = [OptionalForm()] if not error_messages: date_messages = {} else: date_messages = error_messages.copy() if answer['mandatory'] is True: if 'validation' in answer and 'messages' in answer['validation'] \ and 'MANDATORY_DATE' in answer['validation']['messages']: date_messages['MANDATORY_DATE'] = answer['validation']['messages']['MANDATORY_DATE'] validate_with = [DateRequired(message=date_messages['MANDATORY_DATE'])] if 'validation' in answer and 'messages' in answer['validation'] \ and 'INVALID_DATE' in answer['validation']['messages']: date_messages['INVALID_DATE'] = answer['validation']['messages']['INVALID_DATE'] validate_with += [DateCheck(date_messages['INVALID_DATE'])] # Set up all the calendar month choices for select month_choices = [('', 'Select month')] + [(str(x), calendar.month_name[x]) for x in range(1, 13)] DateForm.month = SelectField(choices=month_choices, default='', validators=validate_with) return DateForm
def get_month_year_form(answer, error_messages): """ Returns a month year form metaclass with appropriate validators. Used in both date and date range form creation. :param answer: The answer on which to base this form :param error_messages: The messages to use upon this form during validation :return: The generated MonthYearDateForm metaclass """ class MonthYearDateForm(Form): year = StringField() validate_with = [OptionalForm()] if answer['mandatory'] is True: error_message = error_messages['MANDATORY_DATE'] if 'validation' in answer and 'messages' in answer['validation'] \ and 'MANDATORY_DATE' in answer['validation']['messages']: error_message = answer['validation']['messages']['MANDATORY_DATE'] validate_with = [DateRequired(message=error_message)] if 'validation' in answer and 'messages' in answer['validation'] \ and 'INVALID_DATE' in answer['validation']['messages']: error_message = answer['validation']['messages']['INVALID_DATE'] validate_with += [MonthYearCheck(error_message)] else: validate_with += [MonthYearCheck()] # Set up all the calendar month choices for select month_choices = [('', 'Select month')] + [(str(x), calendar.month_name[x]) for x in range(1, 13)] MonthYearDateForm.month = SelectField(choices=month_choices, default='', validators=validate_with) return MonthYearDateForm
def diffImg(t0, t1, t2): d1 = cv2.absdiff(t2, t1) d2 = cv2.absdiff(t1, t0) return cv2.bitwise_and(d1, d2) #Form Config
def test_form(): # noqa class F(Form): pdf1 = PartialDateField("f1", default=PartialDateDbField(1995), id="test-id-1") pdf2 = PartialDateField("f2", default=PartialDateDbField(2017, 5, 13), id="test-id-2") pdf3 = PartialDateField("f3") csf1 = CountrySelectField() csf2 = CountrySelectField(label="Select Country") bmvf1 = BitmapMultipleValueField(choices=[ ( 1, "one", ), ( 2, "two", ), ( 4, "four", ), ]) bmvf2 = BitmapMultipleValueField( choices=[ ( 1, "one", ), ( 2, "two", ), ( 4, "four", ), ], ) bmvf2.is_bitmap_value = False return F
def make_form(_name='F', **fields): """ Taken from https://github.com/wtforms/wtforms/blob/f5ef784caf/tests/fields.py """ return type(str(_name), (Form, ), fields)