Esempio n. 1
0
 def validate_for_api(self):
     if not super(BaseForm, self).validate():
         message = {'': ""}
         for name, field in iteritems(self._fields):
             if field.errors:
                 current_app.logger.error(
                     'form: %s, name: %s, errors: %s, json_data: %s',
                     self.__class__.__name__, name, field.errors,
                     self.json_data)
                 if isinstance(field, StringField):
                     message = {name: field.errors[0]}
                     break
                 if isinstance(field.errors, list):
                     message = {field.name: field.errors[0]}
                     break
                 elif isinstance(field.errors, dict):
                     for _, _field in iteritems(field.errors):
                         if _field:
                             message = {field.name: _field[0]}
                             break
         print(
             "form: %s, name: %s, errors: %s, json_data: %s" %
             (self.__class__.__name__, name, field.errors, self.json_data))
         return self, ParameterException(message=list(message.values())[0])
     return self, None
Esempio n. 2
0
    def populate_obj(self, obj, ignore_none=False):
        """
        Populates the attributes of the passed `obj` with data from the form's
        fields.

        :note: This is a destructive operation; Any attribute with the same name
               as a field will be overridden. Use with caution.
        """
        if ignore_none:
            for name, field in iteritems(self._fields):
                if field.data is not None:
                    field.populate_obj(obj, name)
        else:
            for name, field in iteritems(self._fields):
                field.populate_obj(obj, name)
Esempio n. 3
0
    def __init__(self, formdata=None, obj=None, prefix="", data=None, meta=None, **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent. formdata should be some sort of request-data wrapper which
            can get multiple parameters from the form input, and values are unicode
            strings, e.g. a Werkzeug/Django/WebOb MultiDict
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param data:
            Accept a dictionary of data. This is only used if `formdata` and
            `obj` are not present.
        :param meta:
            If provided, this is a dictionary of values to override attributes
            on this form's meta instance.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        meta_obj = self._wtforms_meta()
        if meta is not None and isinstance(meta, dict):
            meta_obj.update_values(meta)
        super(Form, self).__init__(self._unbound_fields, meta=meta_obj, prefix=prefix)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)
        self.process(formdata, obj, data=data, **kwargs)
Esempio n. 4
0
    def process(self, formdata=None, obj=None, **kwargs):
        """
        Take form, object data, and keyword arg input and have the fields
        process them.

        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        if formdata is not None and not hasattr(formdata, 'getlist'):
            if hasattr(formdata, 'getall'):
                formdata = WebobInputWrapper(formdata)
            else:
                raise TypeError("formdata should be a multidict-type wrapper that supports the 'getlist' method")

        for name, field, in iteritems(self._fields):
            if obj is not None and hasattr(obj, name):
                field.process(formdata, getattr(obj, name))
            elif name in kwargs:
                field.process(formdata, kwargs[name])
            else:
                field.process(formdata)
Esempio n. 5
0
    def __init__(self, formdata=None, obj=None, prefix="", **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        super(Form, self).__init__(self._unbound_fields, prefix=prefix)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)

        self.process(formdata, obj, **kwargs)
Esempio n. 6
0
    def validate(self, filter=[], extra_validators=None, isParent=False):

        if isParent:
            return super(Form, self).validate()

        self._errors = None
        success = True
        if callable(getattr(self, "_validate", None)):
            _fields = self._validate()
        else:
            _fields = self._fields
        for name, field in iteritems(_fields):
            if name in filter or field in filter:
                continue

            if extra_validators is not None and name in extra_validators:
                extra = extra_validators[name]
            else:
                extra = list()
            inline = getattr(self.__class__, 'validate_%s' % name, None)

            if inline is not None:
                extra.append(inline)

            if not field.validate(self, extra):
                success = False
        return success
Esempio n. 7
0
    def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        super(Form, self).__init__(self._unbound_fields, prefix=prefix)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)

        self.process(formdata, obj, **kwargs)
Esempio n. 8
0
    def __init__(self, formdata=None, obj=None, prefix='', LOCALES=_unset_value, **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent. formdata should be some sort of request-data wrapper which
            can get multiple parameters from the form input, and values are unicode
            strings, e.g. a Werkzeug/Django/WebOb MultiDict
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param LOCALES:
            If provided, this is a sequence of locale name strings that is
            the priority order of locales to try to find validator message
            translations at.
            If `None`, then use the default gettext locale from the environ.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        super(Form, self).__init__(self._unbound_fields, prefix=prefix, LOCALES=LOCALES)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)

        self.process(formdata, obj, **kwargs)
Esempio n. 9
0
    def process(self, formdata=None, obj=None, data=None, **kwargs):
        """
        Take form, object data, and keyword arg input and have the fields
        process them.

        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param data:
            If provided, must be a dictionary of data. This is only used if
            `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as the field.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        formdata = self.meta.wrap_formdata(self, formdata)

        if data is not None:
            # XXX we want to eventually process 'data' as a new entity.
            #     Temporarily, this can simply be merged with kwargs.
            kwargs = dict(data, **kwargs)

        for name, field in iteritems(self._fields):
            if obj is not None and hasattr(obj, name):
                field.process(formdata, getattr(obj, name))
            elif name in kwargs:
                field.process(formdata, kwargs[name])
            else:
                field.process(formdata)
Esempio n. 10
0
    def process(self, formdata=None, obj=None, data=None, **kwargs):
        """
        This is identical to WTForm 2.1's implementation of 'process',
        but it must pass in the User.studies.values() when it's called with
        an object instead of just User.studies, since studies is a mapped
        collection
        """
        formdata = self.meta.wrap_formdata(self, formdata)

        if data is not None:
            # XXX we want to eventually process 'data' as a new entity.
            #     Temporarily, this can simply be merged with kwargs.
            kwargs = dict(data, **kwargs)

        for name, field, in iteritems(self._fields):
            if obj is not None and hasattr(obj, name):
                # This if statement is the only change made to the original
                # code for BaseForm.process() - Dawn
                if name == 'studies':
                    access_rights = []
                    for study in obj.studies:
                        access_rights.extend(obj.studies[study])
                    field.process(formdata, access_rights)
                else:
                    field.process(formdata, getattr(obj, name))
            elif name in kwargs:
                field.process(formdata, kwargs[name])
            else:
                field.process(formdata)
Esempio n. 11
0
 def errors(self):
     """展平error"""
     if self._errors is None:
         self._errors = dict((name, flat_list(f.errors))
                             for name, f in iteritems(self._fields)
                             if f.errors)
     return self._errors
Esempio n. 12
0
    def process(self, formdata=None, obj=None, data=None, **kwargs):
        """
        Take form, object data, and keyword arg input and have the fields
        process them.

        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param data:
            If provided, must be a dictionary of data. This is only used if
            `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as the field.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        formdata = self.meta.wrap_formdata(self, formdata)

        if data is not None:
            # XXX we want to eventually process 'data' as a new entity.
            #     Temporarily, this can simply be merged with kwargs.
            kwargs = dict(data, **kwargs)

        for name, field in iteritems(self._fields):
            if obj is not None and hasattr(obj, name):
                field.process(formdata, getattr(obj, name))
            elif name in kwargs:
                field.process(formdata, kwargs[name])
            else:
                field.process(formdata)
Esempio n. 13
0
    def process(self, formdata=None, obj=None, data=None, **kwargs):
        """
        Overrides wtforms.form.py BaseForm.process.
        Since we're going to load form fields from repeating fields in the object,
        We have to play games with the field names.
        """
        formdata = self.meta.wrap_formdata(self, formdata)

        if data is not None:
            # XXX we want to eventually process 'data' as a new entity.
            #     Temporarily, this can simply be merged with kwargs.
            kwargs = dict(data, **kwargs)

        for name, field, in iteritems(self._fields):
            processed_from_obj = False
            if obj is not None:
                m = re.search(r'^(.+)_([0-6])$', name)
                if m:
                    attr_name = m.group(1)
                    index = int(m.group(2))
                    day_prefs_obj = obj.days[index]
                    if hasattr(day_prefs_obj, attr_name):
                        field.process(formdata, getattr(day_prefs_obj, attr_name))
                        processed_from_obj = True
            if not processed_from_obj:
                if name in kwargs:
                    field.process(formdata, kwargs[name])
                else:
                    field.process(formdata) 
Esempio n. 14
0
def html_params(**kwargs):
    """
    Generate HTML attribute syntax from inputted keyword arguments.

    The output value is sorted by the passed keys, to provide consistent output
    each time this function is called with the same parameters. Because of the
    frequent use of the normally reserved keywords `class` and `for`, suffixing
    these with an underscore will allow them to be used.

    In addition, the values ``True`` and ``False`` are special:
      * ``attr=True`` generates the HTML compact output of a boolean attribute,
        e.g. ``checked=True`` will generate simply ``checked``
      * ``attr=`False`` will be ignored and generate no output.

    >>> html_params(name='text1', id='f', class_='text')
    'class="text" id="f" name="text1"'
    >>> html_params(checked=True, readonly=False, name="text1", abc="hello")
    'abc="hello" checked name="text1"'
    """
    params = []
    for k, v in sorted(iteritems(kwargs)):
        if k in ('class_', 'class__', 'for_'):
            k = k[:-1]
        if v is True:
            params.append(k)
        elif v is False:
            pass
        else:
            params.append('%s="%s"' % (text_type(k), escape(text_type(v), quote=True)))
    return ' '.join(params)
Esempio n. 15
0
def html_params(**kwargs):
    """
    Generate HTML attribute syntax from inputted keyword arguments.

    The output value is sorted by the passed keys, to provide consistent output
    each time this function is called with the same parameters. Because of the
    frequent use of the normally reserved keywords `class` and `for`, suffixing
    these with an underscore will allow them to be used.

    In addition, the values ``True`` and ``False`` are special:
      * ``attr=True`` generates the HTML compact output of a boolean attribute,
        e.g. ``checked=True`` will generate simply ``checked``
      * ``attr=`False`` will be ignored and generate no output.

    >>> html_params(name='text1', id='f', class_='text')
    'class="text" id="f" name="text1"'
    >>> html_params(checked=True, readonly=False, name="text1", abc="hello")
    'abc="hello" checked name="text1"'
    """
    params = []
    for k, v in sorted(iteritems(kwargs)):
        if k in ('class_', 'class__', 'for_'):
            k = k[:-1]
        if v is True:
            params.append(k)
        elif v is False:
            pass
        else:
            params.append('%s="%s"' %
                          (text_type(k), escape(text_type(v), quote=True)))
    return ' '.join(params)
Esempio n. 16
0
    def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent. formdata should be some sort of request-data wrapper which
            can get multiple parameters from the form input, and values are unicode
            strings, e.g. a Werkzeug/Django/WebOb MultiDict
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        super(Form, self).__init__(self._unbound_fields, prefix=prefix)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)

        self.process(formdata, obj, **kwargs)
Esempio n. 17
0
def html_params(**kwargs):
    """
    This is Verbatim from WTForms BUT "aria_" is handled like "data_"

    Generate HTML attribute syntax from inputted keyword arguments.
    The output value is sorted by the passed keys, to provide consistent output
    each time this function is called with the same parameters. Because of the
    frequent use of the normally reserved keywords `class` and `for`, suffixing
    these with an underscore will allow them to be used.
    In order to facilitate the use of ``data-`` attributes, the first underscore
    behind the ``data``-element is replaced with a hyphen.
    >>> html_params(data_any_attribute='something')
    'data-any_attribute="something"'
    In addition, the values ``True`` and ``False`` are special:
      * ``attr=True`` generates the HTML compact output of a boolean attribute,
        e.g. ``checked=True`` will generate simply ``checked``
      * ``attr=False`` will be ignored and generate no output.
    >>> html_params(name='text1', id='f', class_='text')
    'class="text" id="f" name="text1"'
    >>> html_params(checked=True, readonly=False, name="text1", abc="hello")
    'abc="hello" checked name="text1"'
    """
    params = []
    for k, v in sorted(iteritems(kwargs)):
        if k in ('class_', 'class__', 'for_'):
            k = k[:-1]
        elif k.startswith('data_') or k.startswith('aria_') :
            k = k.replace('_', '-', 1)
        if v is True:
            params.append(k)
        elif v is False:
            pass
        else:
            params.append('%s="%s"' % (text_type(k), escape(text_type(v), quote=True)))
    return ' '.join(params)
Esempio n. 18
0
    def process(self, formdata=None, obj=None, **kwargs):
        """
        Take form, object data, and keyword arg input and have the fields
        process them.

        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        if formdata is not None and not hasattr(formdata, 'getlist'):
            if hasattr(formdata, 'getall'):
                formdata = WebobInputWrapper(formdata)
            else:
                raise TypeError(
                    "formdata should be a multidict-type wrapper that supports the 'getlist' method"
                )

        for name, field, in iteritems(self._fields):
            if obj is not None and hasattr(obj, name):
                field.process(formdata, getattr(obj, name))
            elif name in kwargs:
                field.process(formdata, kwargs[name])
            else:
                field.process(formdata)
Esempio n. 19
0
    def __init__(self, formdata=None, obj=None, prefix='', data=None, meta=None, **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent. formdata should be some sort of request-data wrapper which
            can get multiple parameters from the form input, and values are unicode
            strings, e.g. a Werkzeug/Django/WebOb MultiDict
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param data:
            Accept a dictionary of data. This is only used if `formdata` and
            `obj` are not present.
        :param meta:
            If provided, this is a dictionary of values to override attributes
            on this form's meta instance.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        meta_obj = self._wtforms_meta()
        if meta is not None and isinstance(meta, dict):
            meta_obj.update_values(meta)
        super(Form, self).__init__(self._unbound_fields, meta=meta_obj, prefix=prefix)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)
        self.process(formdata, obj, data=data, **kwargs)
Esempio n. 20
0
    def validate(self, filter=[], extra_validators=None, isParent=False):

        if isParent:
            return super(Form, self).validate()

        self._errors = None
        success = True
        if callable(getattr(self, "_validate", None)):
            _fields = self._validate()
        else:
            _fields = self._fields
        for name, field in iteritems(_fields):
            if name in filter or field in filter:
                continue

            if extra_validators is not None and name in extra_validators:
                extra = extra_validators[name]
            else:
                extra = list()
            inline = getattr(self.__class__, 'validate_%s' % name, None)

            if inline is not None:
                extra.append(inline)

            if not field.validate(self, extra):
                success = False
        return success
Esempio n. 21
0
    def patch_data(self):
        data = {}

        for name, f in iteritems(self._fields):
            if f.raw_data and (f.data != f.object_data):
                data[name] = f.data

        return data
Esempio n. 22
0
    def populate_obj(self, obj):
        for name, field in iteritems(self._fields):
            if name in ['site_theme', 'invoice_theme']:
                continue

            field.populate_obj(obj, name)

        obj.site_theme = SiteTheme.query.filter_by(name=self.site_theme.data).first()
        obj.invoice_theme = InvoiceTheme.query.filter_by(name=self.invoice_theme.data).first()
Esempio n. 23
0
    def populate_obj(self, obj):
        for name, field in iteritems(self._fields):
            if not name.startswith('comment_service'):
                field.populate_obj(obj, name)

        csn = self._fields['comment_service_name']
        csi = self._fields['comment_service_id']
        if csn and csi:
            obj.comment_service = '%s-%s' % (csn.data, csi.data)
Esempio n. 24
0
 def data(self):
     for name, f in iteritems(self._fields):
         if f.data is not None:
             if isinstance(f.data, FileStorage):
                 file_name = f.data.filename
                 self._save_file(f.data, file_name)
                 return [{'name': file_name, 'key': self.save_key}]
             else:
                 return [f.data]
Esempio n. 25
0
    def populate_obj(self, obj):
        for name, field in iteritems(self._fields):
            if not name.startswith('comment_service'):
                field.populate_obj(obj, name)

        csn = self._fields['comment_service_name']
        csi = self._fields['comment_service_id']
        if csn and csi:
            obj.comment_service = '%s-%s' % (csn.data, csi.data)
Esempio n. 26
0
    def populate_obj(self, obj):
        """
        Populates the attributes of the passed `obj` with data from the form's
        fields.

        :note: This is a destructive operation; Any attribute with the same name
               as a field will be overridden. Use with caution.
        """
        for name, field in iteritems(self._fields):
            field.populate_obj(obj, name)
Esempio n. 27
0
    def populate_obj(self, obj):
        """
        Populates the attributes of the passed `obj` with data from the forms's
        fields.

        :note: This is a destructive operation; Any attribute with the same name
               as a field will be overridden. Use with caution.
        """
        for name, field in iteritems(self._fields):
            field.populate_obj(obj, name)
Esempio n. 28
0
    def validate_on_submit(self):
        """表单校验"""
        primary_key = request.form.get('primary_key', '').strip()
        ret = super(Form, self).validate_on_submit()
        if ret is True or (not primary_key or primary_key == '0'):
            return ret

        # 编辑更新时文件上传是必填项报错问题
        for name, field, in iteritems(self._fields):
            if (isinstance(field, FileField) is True
                    and field.flags.required
                    and not field.data
                    and field.errors):
                field.errors = ()
        
        for name, field in iteritems(self._fields):
            if field.errors:
                return False

        return True
Esempio n. 29
0
    def data(self):
        """DateRangeField一次提供了多个name"""
        value_map = []
        for name, field in iteritems(self._fields):
            if isinstance(field, DateRangeField):
                # 换成dataset,因为data要用于pre_validate
                for extra_name, value in field.dataset.items():
                    value_map.append((extra_name, value))
            else:
                value_map.append((name, field.data))

        return dict(value_map)
Esempio n. 30
0
    def __init__(self, extra_converters=None, simple_conversions=None):
        converters = {}
        if simple_conversions is None:
            simple_conversions = self.DEFAULT_SIMPLE_CONVERSIONS
        for field_type, django_fields in iteritems(simple_conversions):
            converter = self.make_simple_converter(field_type)
            for name in django_fields:
                converters[name] = converter

        if extra_converters:
            converters.update(extra_converters)
        super(ModelConverter, self).__init__(converters)
Esempio n. 31
0
    def fill_form(self, obj=None, data=None, **kwargs):
        """填充表单"""
        if data is not None:
            # XXX we want to eventually process 'data' as a new entity.
            #     Temporarily, this can simply be merged with kwargs.
            kwargs = dict(data, **kwargs)

        for name, field, in iteritems(self._fields):
            if obj is not None and hasattr(obj, name):
                field.data = getattr(obj, name)
            elif name in kwargs:
                field.data = kwargs[name]
Esempio n. 32
0
    def __init__(self, extra_converters=None, simple_conversions=None):
        converters = {}
        if simple_conversions is None:
            simple_conversions = self.DEFAULT_SIMPLE_CONVERSIONS
        for field_type, django_fields in iteritems(simple_conversions):
            converter = self.make_simple_converter(field_type)
            for name in django_fields:
                converters[name] = converter

        if extra_converters:
            converters.update(extra_converters)
        super(ModelConverter, self).__init__(converters)
Esempio n. 33
0
    def populate_obj(self, obj):
        """
        Populate form to object.

        Since Form's default `populate_obj` function populate all
        the fields in this class, this function will do the same
        function except `emails` field.

        :param obj: Job Model object.
        """
        for name, field in iteritems(self._fields):
            if name not in ['query_time_out', 'emails', 'schedules']:
                field.populate_obj(obj, name)
Esempio n. 34
0
 def populate_obj(self, obj):
     """
     As with process, this implementation is the same as WTForm 2.1's
     default with the 'studies' field treated as a special case to
     account for the fact that it is a mapped collection
     """
     for name, field in iteritems(self._fields):
         if name == 'studies':
             for study_form in self.studies.entries:
                 study_form.form.populate_obj(
                     obj.studies[study_form.study_id.data])
         else:
             field.populate_obj(obj, name)
Esempio n. 35
0
 def populate_obj(self, obj):
     """
     Overrides wtforms.form.py BaseForm.process.
     Since we're going to populate to repeating fields in the object,
     We have to play games with the field names.
     """
     for name, field in iteritems(self._fields):
         m = re.search(r'^(.+)_([0-6])$', name)
         if m:
             attr_name = m.group(1)
             index = int(m.group(2))
             day_prefs_obj = obj.days[index]
             field.populate_obj(day_prefs_obj, attr_name)
Esempio n. 36
0
    def data(self):

        data_list = []

        for name, f in iteritems(self._fields):
            if f.data is not None:
                for key in f.data:
                    # WUJG: 如果对应的值为空字符串或其他逻辑错的内容,我们可以默认设置为0
                    if key != 'type' and key != 'offsetType':
                        f.data[key] = float(f.data[key] or 0)
                    else:
                        f.data[key] = int(f.data[key] or 0)
                data_list.append(f.data)
        return data_list
Esempio n. 37
0
 def errors_with_data(self):
     # Convert lazy_gettext error strings into unicode so they don't cause problems downstream
     # (like when pickling)
     return {
         name: {
             'data':
             f.data,
             'errors': [
                 six.text_type(e) if is_lazy_string(e) else e
                 for e in f.errors
             ]
         }
         for name, f in iteritems(self._fields) if f.errors
     }
Esempio n. 38
0
    def __init__(self, handler=None, **kwargs):
        formdata = MultiValueDict()
        if handler:
            for name in handler.request.arguments.keys():
                formdata.setlist(name, handler.get_arguments(name))

            # we should also iterate over request.files because
            # get_arguments does not return list of filenames
            for field, files in iteritems(handler.request.files):
                names = []
                for file in files:
                    names.append(file['filename'])
                formdata.setlist(field, names)
        super(Form, self).__init__(formdata, **kwargs)
Esempio n. 39
0
    def __init__(self, handler=None, **kwargs):
        formdata = MultiValueDict()
        if handler:
            for name in handler.request.arguments.keys():
                formdata.setlist(name, handler.get_arguments(name))

            # we should also iterate over request.files because
            # get_arguments does not return list of filenames
            for field, files in iteritems(handler.request.files):
                names = []
                for file in files:
                    names.append(file['filename'])
                formdata.setlist(field, names)
        super(Form, self).__init__(formdata, **kwargs)
Esempio n. 40
0
    def populate_obj(self, obj, partial=False):
        """
        Populates the attributes of the passed `obj` with data from the form's
        fields.
        :param partial:
            If True allows for a partial update to be applied to an object
            i.e. only updates attributes if matching field supplied
            in formdata/data/kwargs

        :note: This is a destructive operation; Any attribute with the same name
               as a field will be overridden. Use with caution.
        """
        for name, field in iteritems(self._fields):
            if not partial or (partial and name in self._formkeys):
                field.populate_obj(obj, name)
Esempio n. 41
0
    def populate_obj(self, obj, partial=False):
        """
        Populates the attributes of the passed `obj` with data from the form's
        fields.
        :param partial:
            If True allows for a partial update to be applied to an object
            i.e. only updates attributes if matching field supplied
            in formdata/data/kwargs

        :note: This is a destructive operation; Any attribute with the same name
               as a field will be overridden. Use with caution.
        """
        for name, field in iteritems(self._fields):
            if not partial or (partial and name in self._formkeys):
                field.populate_obj(obj, name)
Esempio n. 42
0
def html_params(**kwargs):
    """
    Generate HTML attribute syntax from inputted keyword arguments.

    The output value is sorted by the passed keys, to provide consistent output
    each time this function is called with the same parameters. Because of the
    frequent use of the normally reserved keywords `class` and `for`, suffixing
    these with an underscore will allow them to be used.

    In order to facilitate the use of ``data-`` and ``aria-`` attributes, if the
    name of the attribute begins with ``data_`` or ``aria_``, then every
    underscore will be replaced with a hyphen in the generated attribute.

    >>> html_params(data_attr='user.name', aria_labeledby='name')
    'data-attr="user.name" aria-labeledby="name"'

    In addition, the values ``True`` and ``False`` are special:
      * ``attr=True`` generates the HTML compact output of a boolean attribute,
        e.g. ``checked=True`` will generate simply ``checked``
      * ``attr=False`` will be ignored and generate no output.

    >>> html_params(name='text1', id='f', class_='text')
    'class="text" id="f" name="text1"'
    >>> html_params(checked=True, readonly=False, name="text1", abc="hello")
    'abc="hello" checked name="text1"'

    .. versionchanged:: 3.0
        ``aria_`` args convert underscores to hyphens like ``data_``
        args.

    .. versionchanged:: 2.2
        ``data_`` args convert all underscores to hyphens, instead of
        only the first one.
    """
    params = []
    for k, v in sorted(iteritems(kwargs)):
        if k in ("class_", "class__", "for_"):
            k = k[:-1]
        elif k.startswith("data_") or k.startswith("aria_"):
            k = k.replace("_", "-")
        if v is True:
            params.append(k)
        elif v is False:
            pass
        else:
            params.append('%s="%s"' % (text_type(k), escape(v)))
    return " ".join(params)
Esempio n. 43
0
def model_fields(model,
                 only=None,
                 exclude=None,
                 field_args=None,
                 converter=None):
    """
    Extracts and returns a dictionary of form fields for a given
    ``db.Model`` class.

    :param model:
        The ``db.Model`` class to extract fields from.
    :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 a 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.
    """
    converter = converter or ModelConverter()
    field_args = field_args or {}

    # Get the field names we want to include or exclude, starting with the
    # full list of model properties.
    props = model.properties()
    sorted_props = sorted(iteritems(props),
                          key=lambda prop: prop[1].creation_counter)
    field_names = list(x[0] for x in sorted_props)

    if only:
        field_names = list(f for f in only if f in field_names)
    elif exclude:
        field_names = list(f for f in field_names if f not in exclude)

    # Create all fields.
    field_dict = {}
    for name in field_names:
        field = converter.convert(model, props[name], field_args.get(name))
        if field is not None:
            field_dict[name] = field

    return field_dict
Esempio n. 44
0
def html_params(**kwargs):
    """
    Generate HTML attribute syntax from inputted keyword arguments.

    The output value is sorted by the passed keys, to provide consistent output
    each time this function is called with the same parameters. Because of the
    frequent use of the normally reserved keywords `class` and `for`, suffixing
    these with an underscore will allow them to be used.

    In order to facilitate the use of ``data-`` and ``aria-`` attributes, if the
    name of the attribute begins with ``data_`` or ``aria_``, then every
    underscore will be replaced with a hyphen in the generated attribute.

    >>> html_params(data_attr='user.name', aria_labeledby='name')
    'data-attr="user.name" aria-labeledby="name"'

    In addition, the values ``True`` and ``False`` are special:
      * ``attr=True`` generates the HTML compact output of a boolean attribute,
        e.g. ``checked=True`` will generate simply ``checked``
      * ``attr=False`` will be ignored and generate no output.

    >>> html_params(name='text1', id='f', class_='text')
    'class="text" id="f" name="text1"'
    >>> html_params(checked=True, readonly=False, name="text1", abc="hello")
    'abc="hello" checked name="text1"'

    .. versionchanged:: 3.0
        ``aria_`` args convert underscores to hyphens like ``data_``
        args.

    .. versionchanged:: 2.2
        ``data_`` args convert all underscores to hyphens, instead of
        only the first one.
    """
    params = []
    for k, v in sorted(iteritems(kwargs)):
        if k in ("class_", "class__", "for_"):
            k = k[:-1]
        elif k.startswith("data_") or k.startswith("aria_"):
            k = k.replace("_", "-")
        if v is True:
            params.append(k)
        elif v is False:
            pass
        else:
            params.append('%s="%s"' % (text_type(k), escape(v)))
    return " ".join(params)
Esempio n. 45
0
    def render(self, context):
        try:
            if "." in self.field_var:
                base, field_name = self.field_var.rsplit(".", 1)
                field = getattr(Variable(base).resolve(context), field_name)
            else:
                field = context[self.field_var]
        except (template.VariableDoesNotExist, KeyError, AttributeError):
            return settings.TEMPLATE_STRING_IF_INVALID

        h_attrs = {}
        for k, v in iteritems(self.html_attrs):
            try:
                h_attrs[k] = v.resolve(context)
            except template.VariableDoesNotExist:
                h_attrs[k] = settings.TEMPLATE_STRING_IF_INVALID

        return field(**h_attrs)
Esempio n. 46
0
    def render(self, context):
        try:
            if '.' in self.field_var:
                base, field_name = self.field_var.rsplit('.', 1)
                field = getattr(Variable(base).resolve(context), field_name)
            else:
                field = context[self.field_var]
        except (template.VariableDoesNotExist, KeyError, AttributeError):
            return settings.TEMPLATE_STRING_IF_INVALID

        h_attrs = {}
        for k, v in iteritems(self.html_attrs):
            try:
                h_attrs[k] = v.resolve(context)
            except template.VariableDoesNotExist:
                h_attrs[k] = settings.TEMPLATE_STRING_IF_INVALID

        return field(**h_attrs)
Esempio n. 47
0
def model_fields(model, only=None, exclude=None, field_args=None,
                 converter=None):
    """
    Extracts and returns a dictionary of form fields for a given
    ``db.Model`` class.

    :param model:
        The ``db.Model`` class to extract fields from.
    :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 a 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.
    """
    converter = converter or ModelConverter()
    field_args = field_args or {}

    # Get the field names we want to include or exclude, starting with the
    # full list of model properties.
    props = model.properties()
    sorted_props = sorted(iteritems(props), key=lambda prop: prop[1].creation_counter)
    field_names = list(x[0] for x in sorted_props)

    if only:
        field_names = list(f for f in only if f in field_names)
    elif exclude:
        field_names = list(f for f in field_names if f not in exclude)

    # Create all fields.
    field_dict = {}
    for name in field_names:
        field = converter.convert(model, props[name], field_args.get(name))
        if field is not None:
            field_dict[name] = field

    return field_dict
Esempio n. 48
0
    def validate(self, extra_validators=None):
        """
        Validates the form by calling `validate` on each field.

        :param extra_validators:
            If provided, is a dict mapping field names to a sequence of
            callables which will be passed as extra validators to the field's
            `validate` method.

        Returns `True` if no errors occur.
        """
        success = True
        for name, field in iteritems(self._fields):
            if extra_validators is not None and name in extra_validators:
                extra = extra_validators[name]
            else:
                extra = tuple()
            if not field.validate(self, extra):
                success = False
        return success
Esempio n. 49
0
    def populate_obj(self, obj, ignore_fields=None):
        """
        Populates the attributes of the passed `obj` with data from the form's
        fields.
        :note: This is a destructive operation; Any attribute with the same name
               as a field will be overridden. Use with caution.
        :param ignore_fields:
            Fields that should not be populated.
        """
        if ignore_fields is None:
            ignore_fields = []

        for name, field in iteritems(self._fields):
            if name in ignore_fields:
                continue

            if isinstance(field, (ExtendedFormField, ExtendedFieldList)):
                field.populate_obj(obj, name, ignore_fields=ignore_fields)
            else:
                field.populate_obj(obj, name)
Esempio n. 50
0
    def validate(self, extra_validators=None):
        """
        Validates the form by calling `validate` on each field.

        :param extra_validators:
            If provided, is a dict mapping field names to a sequence of
            callables which will be passed as extra validators to the field's
            `validate` method.

        Returns `True` if no errors occur.
        """
        self._errors = None
        success = True
        for name, field in iteritems(self._fields):
            if extra_validators is not None and name in extra_validators:
                extra = extra_validators[name]
            else:
                extra = tuple()
            if not field.validate(self, extra):
                success = False
        return success
Esempio n. 51
0
def html_params(**kwargs):
    """
    Generate HTML parameters from inputted keyword arguments.

    The output value is sorted by the passed keys, to provide consistent output
    each time this function is called with the same parameters.  Because of the
    frequent use of the normally reserved keywords `class` and `for`, suffixing
    these with an underscore will allow them to be used.

    >>> html_params(name='text1', id='f', class_='text') == 'class="text" id="f" name="text1"'
    True
    """
    params = []
    for k,v in sorted(iteritems(kwargs)):
        if k in ('class_', 'class__', 'for_'):
            k = k[:-1]
        if v is True:
            params.append(k)
        else:
            params.append('%s="%s"' % (text_type(k), escape(text_type(v), quote=True)))
    return ' '.join(params)
 def data(self):
     return dict((name, f.data) for name, f in iteritems(self._fields)
                 if name not in self.MEETING_FLAGS)
 def meeting_flags_data(self):
     return dict((name, f.data) for name, f in iteritems(self._fields)
                 if name in self.MEETING_FLAGS)
	def defaults(self):
		return dict((name, f.default) for name,f in list(filter(lambda x: x[1].type not in ('SubmitField','ResetField') and x[1].default,iteritems(self._fields))))
Esempio n. 55
0
 def errors(self):
     return dict((name, f.errors) for name, f in iteritems(self._fields) if f.errors)
Esempio n. 56
0
 def errors(self):
     if self._errors is None:
         self._errors = dict((name, f.errors) for name, f in iteritems(self._fields) if f.errors)
     return self._errors
Esempio n. 57
0
 def data(self):
     return dict((name, f.data) for name, f in iteritems(self._fields))
Esempio n. 58
0
 def errors_with_data(self):
     return {name: {'data': f.data, 'errors': f.errors} for name, f in iteritems(self._fields) if f.errors}
Esempio n. 59
0
 def __init__(self, **kwargs):
     for k, v in iteritems(kwargs):
         setattr(self, k, v)