Example #1
0
 def test_value_coercion(self):
     form = self.F(DummyPostData(b=[u('2')]))
     self.assertEqual(form.b.data, 2)
     self.assert_(form.b.validate(form))
     form = self.F(DummyPostData(b=[u('b')]))
     self.assertEqual(form.b.data, None)
     self.assert_(not form.b.validate(form))
Example #2
0
 def test_defaults(self):
     form = self.F()
     self.assertEqual(form.a.data, u('a'))
     self.assertEqual(form.b.data, None)
     self.assertEqual(form.validate(), False)
     self.assertEqual(form.a(), u("""<select id="a" name="a"><option selected="selected" value="a">hello</option><option value="btest">bye</option></select>"""))
     self.assertEqual(form.b(), u("""<select id="b" name="b"><option value="1">Item 1</option><option value="2">Item 2</option></select>"""))
Example #3
0
 def process_formdata(self, valuelist):
     if valuelist:
         try:
             lat, lon = valuelist[0].split(',')
             self.data = u('%s,%s') % (decimal.Decimal(lat.strip()), decimal.Decimal(lon.strip()),)
         except (decimal.InvalidOperation, ValueError):
             raise ValueError(u('Not a valid coordinate location'))
Example #4
0
 def test_defaults_display(self):
     f = self.F(a=datetime(2001, 11, 15))
     self.assertEqual(f.a.data, datetime(2001, 11, 15))
     self.assertEqual(f.a._value(), u('2001-11-15 00:00'))
     self.assertEqual(f.b.data, date(2004, 9, 12))
     self.assertEqual(f.b._value(), u('2004-09-12'))
     self.assertEqual(f.c.data, None)
     self.assert_(f.validate())
Example #5
0
 def test(self):
     form = self.F()
     self.assertEqual(form.a.data, u('a'))
     self.assertEqual(form.b.data, None)
     self.assertEqual(form.validate(), False)
     self.assertEqual(form.a(), u("""<ul id="a"><li><input checked="checked" id="a-0" name="a" type="radio" value="a" /> <label for="a-0">hello</label></li><li><input id="a-1" name="a" type="radio" value="b" /> <label for="a-1">bye</label></li></ul>"""))
     self.assertEqual(form.b(), u("""<ul id="b"><li><input id="b-0" name="b" type="radio" value="1" /> <label for="b-0">Item 1</label></li><li><input id="b-1" name="b" type="radio" value="2" /> <label for="b-1">Item 2</label></li></ul>"""))
     self.assertEqual([unicode(x) for x in form.a], [u('<input checked="checked" id="a-0" name="a" type="radio" value="a" />'), u('<input id="a-1" name="a" type="radio" value="b" />')])
Example #6
0
    def __init__(self, label=u(''), validators=None, filters=tuple(),
                 description=u(''), id=None, default=None, widget=None,
                 _form=None, _name=None, _prefix='', _translations=None):
        """
        Construct a new field.

        :param label:
            The label of the field. Available after construction through the
            `label` property.
        :param validators:
            A sequence of validators to call when `validate` is called.
        :param filters:
            A sequence of filters which are run on input data by `process`.
        :param description:
            A description for the field, typically used for help text.
        :param id:
            An id to use for the field. A reasonable default is set by the form,
            and you shouldn't need to set this manually.
        :param default:
            The default value to assign to the field, if no form or object
            input is provided. May be a callable.
        :param widget:
            If provided, overrides the widget used to render the field.
        :param _form:
            The form holding this field. It is passed by the form itself during
            construction. You should never pass this value yourself.
        :param _name:
            The name of this field, passed by the enclosing form during its
            construction. You should never pass this value yourself.
        :param _prefix:
            The prefix to prepend to the form name of this field, passed by
            the enclosing form during construction.

        If `_form` and `_name` isn't provided, an :class:`UnboundField` will be
        returned instead. Call its :func:`bind` method with a form instance and
        a name to construct the field.
        """
        self.short_name = _name
        self.name = _prefix + _name
        if _translations is not None:
            self._translations = _translations
        self.id = id or self.name
        self.label = Label(self.id, label or _name.replace('_', ' ').title())
        if validators is None:
            validators = []
        self.validators = validators
        self.filters = filters
        self.description = description
        self.type = type(self).__name__
        self.default = default
        self.raw_data = None
        if widget:
            self.widget = widget
        self.flags = Flags()
        for v in validators:
            flags = getattr(v, 'field_flags', ())
            for f in flags:
                setattr(self.flags, f, True)
Example #7
0
 def test_single_default_value(self):
     first_test = self.sess.query(self.Test).get(2)
     class F(Form):
         a = QuerySelectMultipleField(get_label='name', default=[first_test],
             widget=LazySelect(), query_factory=lambda: self.sess.query(self.Test))
     form = F()
     self.assertEqual([v.id for v in form.a.data], [2])
     self.assertEqual(form.a(), [(u('1'), 'apple', False), (u('2'), 'banana', True)])
     self.assert_(form.validate())
Example #8
0
    def test(self):
        # ListWidget just expects an iterable of field-like objects as its
        # 'field' so that is what we will give it
        field = DummyField([DummyField(x, label='l' + x) for x in ['foo', 'bar']], id='hai')

        self.assertEqual(ListWidget()(field), u('<ul id="hai"><li>lfoo: foo</li><li>lbar: bar</li></ul>'))

        w = ListWidget(html_tag='ol', prefix_label=False)
        self.assertEqual(w(field), u('<ol id="hai"><li>foo lfoo</li><li>bar lbar</li></ol>'))
Example #9
0
 def test(self):
     form = self.F()
     self.assertEqual(form.a.data, None)
     self.assertEqual(form.a(), u("""<input id="a" name="a" type="text" value="" />"""))
     form = self.F(DummyPostData(a=['hello']))
     self.assertEqual(form.a.data, u('hello'))
     self.assertEqual(form.a(), u("""<input id="a" name="a" type="text" value="hello" />"""))
     form = self.F(DummyPostData(b=['hello']))
     self.assertEqual(form.a.data, u(''))
Example #10
0
 def test_prefixes(self):
     form = self.get_form(prefix='foo')
     self.assertEqual(form['test'].name, 'foo-test')
     self.assertEqual(form['test'].short_name, 'test')
     self.assertEqual(form['test'].id, 'foo-test')
     form = self.get_form(prefix='foo.')
     form.process(DummyPostData({'foo.test': [u('hello')], 'test': [u('bye')]}))
     self.assertEqual(form['test'].data, u('hello'))
     self.assertEqual(self.get_form(prefix='foo[')['test'].name, 'foo[-test')
Example #11
0
 def test(self):
     d = datetime(2008, 5, 5, 4, 30, 0, 0)
     form = self.F(DummyPostData(a=['2008-05-05', '04:30:00'], b=['2008-05-05 04:30']))
     self.assertEqual(form.a.data, d)
     self.assertEqual(form.a(), u("""<input id="a" name="a" type="text" value="2008-05-05 04:30:00" />"""))
     self.assertEqual(form.b.data, d)
     self.assertEqual(form.b(), u("""<input id="b" name="b" type="text" value="2008-05-05 04:30" />"""))
     self.assert_(form.validate())
     form = self.F(DummyPostData(a=['2008-05-05']))
     self.assert_(not form.validate())
     self.assert_("not match format" in form.a.errors[0])
Example #12
0
 def test_quantize(self):
     F = make_form(a=DecimalField(places=3, rounding=ROUND_UP), b=DecimalField(places=None))
     form = F(a=Decimal('3.1415926535'))
     self.assertEqual(form.a._value(), u('3.142'))
     form.a.rounding = ROUND_DOWN
     self.assertEqual(form.a._value(), u('3.141'))
     self.assertEqual(form.b._value(), u(''))
     form = F(a=3.14159265, b=72)
     self.assertEqual(form.a._value(), u('3.142'))
     self.assert_(isinstance(form.a.data, float))
     self.assertEqual(form.b._value(), u('72'))
Example #13
0
 def test_without_factory(self):
     sess = self.Session()
     self._fill(sess)
     class F(Form):
         a = QuerySelectField(get_label='name', widget=LazySelect(), get_pk=lambda x: x.id)
     form = F(DummyPostData(a=['1']))
     form.a.query = sess.query(self.Test)
     self.assert_(form.a.data is not None)
     self.assertEqual(form.a.data.id, 1)
     self.assertEqual(form.a(), [(u('1'), 'apple', True), (u('2'), 'banana', False)])
     self.assert_(form.validate())
Example #14
0
    def test_multiple_values_without_query_factory(self):
        form = self.F(DummyPostData(a=['1', '2']))
        form.a.query = self.sess.query(self.Test)
        self.assertEqual([1, 2], [v.id for v in form.a.data])
        self.assertEqual(form.a(), [(u('1'), 'apple', True), (u('2'), 'banana', True)])
        self.assert_(form.validate())

        form = self.F(DummyPostData(a=['1', '3']))
        form.a.query = self.sess.query(self.Test)
        self.assertEqual([x.id for x in form.a.data], [1])
        self.assert_(not form.validate())
Example #15
0
 def test_with_obj(self):
     obj = AttrDict(a=AttrDict(a=u('mmm')))
     form = self.F1(obj=obj)
     self.assertEqual(form.a.form.a.data, u('mmm'))
     self.assertEqual(form.a.form.b.data, None)
     obj_inner = AttrDict(a=None, b='rawr')
     obj2 = AttrDict(a=obj_inner)
     form.populate_obj(obj2)
     self.assert_(obj2.a is obj_inner)
     self.assertEqual(obj_inner.a, u('mmm'))
     self.assertEqual(obj_inner.b, None)
Example #16
0
 def test(self):
     F = make_form(a=DecimalField())
     form = F(DummyPostData(a='2.1'))
     self.assertEqual(form.a.data, Decimal('2.1'))
     self.assertEqual(form.a._value(), u('2.1'))
     form.a.raw_data = None
     self.assertEqual(form.a._value(), u('2.10'))
     self.assert_(form.validate())
     form = F(DummyPostData(a='2,1'), a=Decimal(5))
     self.assertEqual(form.a.data, Decimal(5))
     self.assertEqual(form.a.raw_data, ['2,1'])
     self.assert_(not form.validate())
Example #17
0
    def __init__(self, label=u(''), validators=None, reference_class=None,
                 label_attr=None, allow_blank=False, blank_text=u(''), **kwargs):
        super(ReferencePropertyField, self).__init__(label, validators,
                                                     **kwargs)
        self.label_attr = label_attr
        self.allow_blank = allow_blank
        self.blank_text = blank_text
        self._set_data(None)
        if reference_class is None:
            raise TypeError('Missing reference_class attribute in '
                             'ReferencePropertyField')

        self.query = reference_class.all()
Example #18
0
 def test_field_adding(self):
     form = self.get_form()
     self.assertEqual(len(list(form)), 1)
     form['foo'] = TextField()
     self.assertEqual(len(list(form)), 2)
     form.process(DummyPostData(foo=[u('hello')]))
     self.assertEqual(form['foo'].data, u('hello'))
     form['test'] = IntegerField()
     self.assert_(isinstance(form['test'], IntegerField))
     self.assertEqual(len(list(form)), 2)
     self.assertRaises(AttributeError, getattr, form['test'], 'data')
     form.process(DummyPostData(test=[u('1')]))
     self.assertEqual(form['test'].data, 1)
     self.assertEqual(form['foo'].data, u(''))
Example #19
0
 def pre_validate(self, form):
     if not self.allow_blank or self.data is not None:
         for obj in self.query:
             if str(self.data) == str(obj.key()):
                 break
         else:
             raise ValueError(self.gettext(u('Not a valid choice')))
Example #20
0
 def process_formdata(self, valuelist):
     if valuelist:
         if self.allow_blank and valuelist[0] == u('__None'):
             self.data = None
         else:
             self._data = None
             self._formdata = valuelist[0]
Example #21
0
    def iter_choices(self):
        if self.allow_blank:
            yield (u('__None'), self.blank_text, self.data is None)

        for obj in self.queryset:
            label = self.label_attr and getattr(obj, self.label_attr) or obj
            yield (obj.pk, label, obj == self.data)
Example #22
0
 def pre_validate(self, form):
     if not self.allow_blank or self.data is not None:
         for pk, obj in self._get_object_list():
             if self.data == obj:
                 break
         else:
             raise ValidationError(self.gettext(u('Not a valid choice')))
Example #23
0
 def __iter__(self):
     opts = dict(widget=self.option_widget, _name=self.name, _form=None)
     for i, (value, label, checked) in enumerate(self.iter_choices()):
         opt = self._Option(label=label, id=u('%s-%d') % (self.id, i), **opts)
         opt.process(None, value)
         opt.checked = checked
         yield opt
Example #24
0
 def _value(self):
     if self.raw_data:
         return self.raw_data[0]
     elif self.data is not None:
         return unicode(self.data)
     else:
         return u('')
Example #25
0
 def __init__(self, label=u(''), validators=None, queryset=None, label_attr='', allow_blank=False, blank_text=u(''), **kwargs):
     super(QuerySetSelectField, self).__init__(label, validators, **kwargs)
     self.label_attr = label_attr
     self.allow_blank = allow_blank
     self.blank_text = blank_text
     self._set_data(None)
     if queryset is not None:
         self.queryset = queryset.all() # Make sure the queryset is fresh
Example #26
0
    def iter_choices(self):
        if self.allow_blank:
            yield (u('__None'), self.blank_text, self.data is None)

        for obj in self.query:
            key = str(obj.key())
            label = self.label_attr and getattr(obj, self.label_attr) or str(obj)
            yield (key, label, key == self.data)
Example #27
0
 def pre_validate(self, form):
     if self._invalid_formdata:
         raise ValidationError(self.gettext(u('Not a valid choice')))
     elif self.data:
         obj_list = list(x[1] for x in self._get_object_list())
         for v in self.data:
             if v not in obj_list:
                 raise ValidationError(self.gettext('Not a valid choice'))
Example #28
0
 def _value(self):
     if self.raw_data:
         return self.raw_data[0]
     elif self.data is not None:
         if self.places is not None:
             if hasattr(self.data, 'quantize'):
                 exp = decimal.Decimal('.1') ** self.places
                 quantized = self.data.quantize(exp, rounding=self.rounding)
                 return unicode(quantized)
             else:
                 # If for some reason, data is a float or int, then format
                 # as we would for floats using string formatting.
                 format = u('%%0.%df') % self.places
                 return format % self.data
         else:
             return unicode(self.data)
     else:
         return u('')
Example #29
0
 def __init__(self, form_class, label=u(''), validators=None, separator='-', **kwargs):
     super(FormField, self).__init__(label, validators, **kwargs)
     self.form_class = form_class
     self.separator = separator
     self._obj = None
     if self.filters:
         raise TypeError('FormField cannot take filters, as the encapsulated data is not mutable.')
     if validators:
         raise TypeError('FormField does not accept any validators. Instead, define them on the enclosed form.')
Example #30
0
 def process_formdata(self, valuelist):
     if valuelist:
         date_str = u(' ').join(valuelist)
         try:
             timetuple = time.strptime(date_str, self.format)
             self.data = datetime.date(*timetuple[:3])
         except ValueError:
             self.data = None
             raise