formbar / formbar / form.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
import logging
import datetime
import sqlalchemy as sa
from formencode import htmlfill, variabledecode
from formbar.renderer import FormRenderer, get_renderer

log = logging.getLogger(__name__)


def get_attributes(cls):
    return [prop.key for prop in sa.orm.class_mapper(cls).iterate_properties
            if isinstance(prop, sa.orm.ColumnProperty)
            or isinstance(prop, sa.orm.RelationshipProperty)]


def get_relations(cls):
    return [prop.key for prop in sa.orm.class_mapper(cls).iterate_properties
            if isinstance(prop, sa.orm.RelationshipProperty)]


class Error(Exception):
    """Base class for exceptions in this module."""
    pass


class StateError(Error):
    """Exception raised for state errors while processing the form.

        :msg:  explanation of the error
    """

    def __init__(self, msg):
        self.msg = msg


class Validator(object):
    """Docstring for Validator"""

    def __init__(self, field, error, callback):
        """@todo: to be defined

        :field: @todo
        :error: @todo
        :callback: @todo

        """
        self._field = field
        self._error = error
        self._callback = callback

    def check(self, data):
        return self._callback(self._field, data)


class Form(object):
    """Class for forms. The form will take care for rendering the form,
    validating the submitted data and saving the data back to the
    item.

    The form must be instanciated with an instance of an ``Form``
    configuration and optional an SQLAlchemy mapped item.

    If an SQLAlchemy mapped item is provided there are some basic
    validation is done based on the defintion in the database. Further
    the save method will save the values directly into the database.

    If no item was provided than a dummy item will be created with the
    attributes of the configured fields in the form.
    """

    def __init__(self, config, item=None, dbsession=None, translate=None,
                 change_page_callback={}, renderers={}, request=None,
                 csrf_token=None):
        """Initialize the form with ``Form`` configuration instance and
        optional an SQLAlchemy mapped object.

        :config: FormConfiguration.
        :item: SQLAlchemy mapped instance
        :dbsession: dbsession
        :translate: Translation function which returns a translated
        string for a given msgid
        :set_page_callback: Url which will be called when the user
        changes the currently selected page.
        :renderers: A optional dictionary of custom renderers which are
        provided to the form to render specific form elements. The key
        is the type of the renderer as named in the formular
        configuration.
        :request: Current request (See
        http://docs.pylonsproject.org/projects/pyramid/en/latest/api/request.html
        when using in connection with ringo)
        :csrf_token: Token to which will be included as hidden field in
        the form to prevent CSRF attacks.

        """
        self._config = config
        self._item = item
        self._dbsession = dbsession
        self._request = request
        self._csrf_token = csrf_token
        if translate:
            self._translate = translate
        else:
            self._translate = lambda msgid: msgid

        self.validated = False
        """Flag to indicate if the form has been validated. Init value
        is False.  which means no validation has been done."""
        self.external_validators = []
        """List with external validators. Will be called an form validation."""
        self.current_page = 0
        """Number of the currently selected page"""
        self.change_page_callback = change_page_callback
        """Dictionary with some parameters used to call an URL when the
        user changes the currently selected page. The dictionary has the
        following keys:
         * url: Name of the URL which will be called
         * item (optional): A string which is send to the URL as GET
           paramenter. Often this is the name of the element (clazzname)
         * itemid (optional): The id of the currently editied element.
        The url will have the additional parameter "page" which holds
        the currently selected page.
        """
        self.external_renderers = renderers
        """Dictionary with external provided custom renderers."""
        self.fields = self._build_fields()
        """Dictionary with fields."""
        self.data = {}
        """After submission this Dictionary will contain the
        validated data on successfull validation. Else this Dictionary
        will be empty"""
        self.submitted_data = {}
        """The submitted data from the user. If validation fails, then
        this values are used to rerender the form."""
        self.loaded_data = self.serialize(self._get_data_from_item())
        """This is the initial data loaded from the given item. Used to
        render the readonly forms"""

    def _get_data_from_item(self):
        values = {}
        if not self._item:
            return values
        for name, field in self._config.get_fields().iteritems():
            try:
                values[name] = getattr(self._item, name)
            except AttributeError:
                values[name] = None
        return values

    def _filter_values(self, values):
        """Will return a filtered dictionary of the given values
        dictionary which only contains values which are actually part of
        the current form.

        :values: Dicionary with unfilterd values
        :returns: Dicionary with filtered values

        """
        filtered = {}
        for fieldname, field in self.fields.iteritems():
            if values.has_key(fieldname):
                filtered[fieldname] = values[fieldname]
        return filtered

    def deserialize(self, data):
        """Returns a dictionary with pythonized data data. Usually this
        is the submitted data coming from a form. The dictionary will
        include all values provided in the initial data dictionary
        converted into python datatype.

        :data: Dictionary with serialized data
        :returns: Dictionary with deserialized data

        """
        deserialized = {}
        for fieldname, value in self._filter_values(data).iteritems():
            field = self.fields.get(fieldname)
            deserialized[fieldname] = self._to_python(field, data.get(field.name))
        log.debug("Deserialized values: %s" % deserialized)
        return deserialized

    def serialize(self, data):
        """Returns a dictionary with serialized data from the forms
        item.  The return dictionary is suitable for htmlfill to prefill
        the rendered form. The dictionary will include all attributes
        and relations values of the items. The key in the dictionary is
        the name of the relation/attribute. In case of relations the
        value in the dictionary is the "id" value of the related item.
        If no item is present then return a empty dict.

        :returns: Dictionary with serialized values of the item.

        """
        serialized = {}
        for fieldname, value in self._filter_values(data).iteritems():
            field = self.fields.get(fieldname)
            #if field and not field.is_readonly():
            #    # Only add the value if the field is not marked as readonly
            #    serialized[fieldname] = self._from_python(field, value)
            serialized[fieldname] = self._from_python(field, value)
        log.debug("Serialized values: %s" % serialized)
        return serialized

    def _build_fields(self):
        """Returns a dictionary with all Field instances which are
        configured for this form.
        :returns: Dictionary with Field instances

        """
        fields = {}
        for name, field in self._config.get_fields().iteritems():
            fields[name] = Field(self, field, self._translate)
        return fields

    def has_errors(self):
        """Returns True if one of the fields in the form has errors"""
        for field in self.fields.values():
            if len(field.get_errors()) > 0:
                return True
        return False

    def has_warnings(self):
        """Returns True if one of the fields in the form has warnings"""
        for field in self.fields.values():
            if len(field.get_warnings()) > 0:
                return True
        return False

    def get_errors(self, page=None):
        """Returns a dictionary of all errors in the form. If page
        parameter is given, then only the errors for fields on the given
        page are returned. This dictionary will contain the errors if
        the validation fails. The key of the dictionary is the fieldname
        of the field.  As a field can have more than one error the value
        is a list.

        :page: Dictionary with errors
        :returns: Dictionary with errors
        """
        if page is not None:
            fields_on_page = self._config.get_fields(page)

        errors = {}
        for field in self.fields.values():
            if page is not None and field.name not in fields_on_page: continue
            if len(field.get_errors()) > 0:
                errors[field.name] = field.get_errors()
        return errors

    def get_warnings(self, page=None):
        """Returns a dictionary of all warnings in the form. If page
        parameter is given, then only the warnings for fields on the given
        page are returned. This dictionary will contain the warnings if
        the validation fails. The key of the dictionary is the fieldname
        of the field.  As a field can have more than one warning the value
        is a list.

        :page: Name of the page
        :returns: Dictionary with warnings
        """
        if page is not None:
            fields_on_page = self._config.get_fields(page)

        warnings = {}
        for field in self.fields.values():
            if page is not None and field.name not in fields_on_page: continue
            if len(field.get_warnings()) > 0:
                warnings[field.name] = field.get_warnings()
        return warnings

    def get_field(self, name):
        return self.fields[name]

    def add_validator(self, validator):
        return self.external_validators.append(validator)

    def render(self, values={}, page=0, buttons=True, previous_values=None):
        """Returns the rendererd form as an HTML string.

        :values: Dictionary with values to be prefilled/overwritten in
        the rendered form.
        :previous_values: Dictionary of values of the last saved state
        of the item. If provided a diff between the current and previous
        values will be renderered in readonly mode.
        :returns: Rendered form.

        """
        self.current_page = page

        if self.submitted_data:
            item_values = self.submitted_data
        else:
            item_values = self.loaded_data
        # Merge the items_values with the extra provided values. Extra
        # values will overwrite the item_values.
        values = dict(item_values.items() + values.items())

        # Add csrf_token to the values dictionary
        values['csrf_token'] = self._csrf_token

        renderer = FormRenderer(self, self._translate)
        form = renderer.render(values=values, buttons=buttons,
                               previous_values=previous_values)
        try:
            return htmlfill.render(form, values)
        except AssertionError, e:
            log.error("Error while parsing form in htmlfill: %s. Hint See 'https://github.com/formencode/formencode/issues/57'" % e.message)

    def _add_error(self, fieldname, error):
        field = self.get_field(fieldname)
        if isinstance(error, list):
            for err in error:
                field.add_error(err)
        else:
            field.add_error(error)

    def _add_warning(self, fieldname, warning):
        field = self.get_field(fieldname)
        if isinstance(warning, list):
            for war in warning:
                field.add_warning(war)
        else:
            field.add_warning(warning)

    def _to_python(self, field, value):
        """Returns a value of python datatype converted from the
        stringvalue depending of the fields datatype

        :field: configuration of the field
        :value: value to be converted
        """
        relation_names = {}
        try:
            mapper = sa.orm.object_mapper(self._item)
            relation_properties = filter(
                lambda p: isinstance(p, sa.orm.properties.RelationshipProperty),
                mapper.iterate_properties)
            for prop in relation_properties:
                relation_names[prop.key] = prop
        except sa.orm.exc.UnmappedInstanceError:
            if not self._item:
                pass # The form is not mapped to an item.
            else:
                raise

        converted = ""
        dtype = field.get_type()
        if dtype == 'string':
            try:
                converted = value
            except ValueError:
                msg = "%s is not a string value." % value
                self._add_error(field.name, msg)
        elif dtype == 'integer':
            if not value:
                return None
            try:
                converted = int(value)
            except ValueError:
                msg = "%s is not a integer value." % value
                self._add_error(field.name, msg)
        elif dtype == 'float':
            if not value:
                return None
            try:
                converted = float(value)
            except ValueError:
                msg = "%s is not a float value." % value
                self._add_error(field.name, msg)
        elif dtype == 'boolean':
            if not value:
                return None
            try:
                converted = value in ['True', '1', 't']
            except ValueError:
                msg = "%s is not a boolean value." % value
                self._add_error(field.name, msg)
        elif dtype == 'file':
            try:
                # filename = value.filename
                converted = value.file.read()
            except AttributeError:
                return None
            except ValueError:
                msg = "%s is not a file value." % value
                self._add_error(field.name, msg)
        elif dtype == 'date':
            if not value:
                return None
            try:
                #@TODO: Support other dateformats that ISO8601
                y, m, d = value.split('-')
                y = int(y)
                m = int(m)
                d = int(d)
                try:
                    converted = datetime.date(y, m, d)
                except ValueError, e:
                    msg = "%s is an invalid date (%s)" % (value, e)
                    self._add_error(field.name, msg)
            except:
                msg = "%s is not a valid date format." % value
                self._add_error(field.name, msg)
        elif dtype == 'time':
            if not value:
                return None
            try:
                h, m, s = value.split(':')
                h = int(h)
                m = int(m)
                s = int(s)
                converted = datetime.timedelta(hours=h, minutes=m, seconds=s).total_seconds()
            except ValueError:
                msg = "Value '%s' must be in format 'HH:MM:SS'" % value
                self._add_error(field.name, msg)
        elif dtype == 'datetime':
            if not value:
                return None
            try:
                tmpdate = value.split(' ')
                # Time is optional. If not provided set time to 00:00:00
                if len(tmpdate) == 2:
                    date, time = value.split(' ')
                else:
                    date = tmpdate[0]
                    time = "00:00:00"
                y, m, d = date.split('-')
                y = int(y)
                m = int(m)
                d = int(d)
                h, M, s = time.split(':')
                h = int(h)
                M = int(M)
                s = int(s)
                converted = datetime.datetime(y, m, d, h, M, s)
            except:
                log.exception("e")
                msg = "%s is not a valid datetime format." % value
                self._add_error(field.name, msg)
        # Reltation handling
        elif dtype == 'manytoone':
            try:
                db = self._dbsession
                rel = relation_names[field.name].mapper.class_
                if value in ("", None):
                    converted = None
                else:
                    value = db.query(rel).filter(rel.id == int(value)).one()
                    converted = value
            except ValueError:
                msg = "Reference value '%s' must be of type integer" % value
                self._add_error(field.name, msg)
        elif dtype in ['onetomany', 'manytomany']:
            if not value:
                return []

            # In case the there is only one linked item, the value
            # is a string value und not a list. In this case we
            # need to put the value into a list to make the loading
            # and reasinging of items work. Otherwise a item with id
            # 670 will be converted into a list containing 6, 7, 0
            # which will relink different items!
            if not isinstance(value, list):
                value = [value]

            try:
                values = []
                db = self._dbsession
                rel = relation_names[field.name].mapper.class_
                for v in value:
                    values.append(db.query(rel).filter(rel.id == int(v)).one())
                converted = values
            except ValueError:
                msg = "Reference value '%s' must be of type integer" % value
                self._add_error(field.name, msg)
        log.debug("Converted value '%s' (%s) of field '%s' (%s)"
                  % (converted, type(converted), field.name, dtype))
        return converted

    def _from_python(self, field, value):
        """@todo: Docstring for _from_python.

        :field: @todo
        :value: @todo
        :returns: @todo

        """
        serialized = ""
        ftype = field.get_type()
        try:
            if value is None:
                serialized = ""
            elif isinstance(value, basestring):
                serialized = value
            elif isinstance(value, list):
                vl = []
                for v in value:
                    try:
                        vl.append(v.id)
                    except AttributeError:
                        vl.append(v)
                serialized = vl
            else:
                try:
                    serialized = value.id
                except AttributeError:
                    if ftype == "time":
                        td = datetime.timedelta(seconds=int(value))
                        d = datetime.datetime(1, 1, 1) + td
                        serialized = "%02d:%02d:%02d" % (d.hour, d.minute, d.second)
                    elif ftype == "datetime":
                        serialized = value.strftime("%Y-%m-%d %H:%M:%S")
                    else:
                        serialized = value
        except AttributeError:
            log.warning('Can not get value for field "%s". '
                        'The field is no attribute of the item' % field.name)
        return serialized

    def validate(self, submitted):
        """Returns True if the validation succeeds else False.
        Validation of the data happens in three stages:

        1. Prevalidation. Custom rules that are checked before any
        datatype checks on type conversations are made.
        2. Basic type checks and type conversation. Type checks and type
        conversation is done based on the data type of the field and
        further constraint defined in the database if the form is
        instanciated with an SQLAlchemy mapped item.
        3. Postvalidation. Custom rules that are checked after the type
        conversation was done.

        All errors are stored in the errors dictionary through the
        process of validation. After the validation finished the values
        are stored in the data dictionary. In case there has been errors
        the dictionary will contain the origin submitted data.

        :submitted: Dictionary with submitted values.
        :returns: True or False

        """

        if not submitted:
            unvalidated = self.loaded_data
            # No need to convert the values here as the values are
            # already pythonic when loaded from the item.
            converted = unvalidated
        else:
            self.submitted_data = variabledecode.variable_decode(submitted)
            unvalidated = self.submitted_data
            converted = self.deserialize(unvalidated)

        # Validate the fields. Ignore fields which are disabled in
        # conditionals First get list of fields which are still in the
        # form after conditionals has be evaluated
        fields_to_check = self._config.get_fields(values=converted,
                                                  reload_fields=True,
                                                  evaluate=True)
        for fieldname, field in fields_to_check.iteritems():
            field = self.fields[fieldname]
            for rule in field.get_rules():
                if rule.mode == "pre":
                    result = rule.evaluate(unvalidated)
                else:
                    result = rule.evaluate(converted)
                if not result:
                    if rule.triggers == "warning":
                        self._add_warning(fieldname, rule.msg)
                    else:
                        self._add_error(fieldname, rule.msg)

        # Custom validation. User defined external validators.
        for validator in self.external_validators:
            if not validator.check(converted):
                self._add_error(validator._field, validator._error)

        # If the form is valid. Save the converted and validated data
        # into the data dictionary. If not, than save the origin
        # submitted data.
        has_errors = self.has_errors()
        if not has_errors:
            self.data = converted
        self.validated = True
        return not has_errors

    def save(self):
        """Will save the validated data back into the item. In case of
        an SQLAlchemy mapped item the data will be stored into the
        database.
        :returns: Item with validated data.

        """
        if not self.validated:
            raise StateError('Saving is not possible without prior validation')
        if self.has_errors():
            raise StateError('Saving is not possible if form has errors')

        # Only save if there is actually an item.
        if self._item is not None:
            # TODO: Iterate over fields here. Fields should know their value
            # and if they are a relation or not (torsten) <2013-07-24 23:24>
            for key, value in self.data.iteritems():
                setattr(self._item, key, value)
            # If the item has no id, then we assume it is a new item. So
            # add it to the database session.
            if not self._item.id:
                self._dbsession.add(self._item)
        return self._item


class Field(object):
    """Wrapper for fields in the form. The purpose of this class is to
    provide a common interface for the renderer independent to the
    underlying implementation detail of the field."""

    def __init__(self, form, config, translate):
        """Initialize the field with the given field configuration.

        :config: Field configuration

        """
        self._form = form
        self._config = config
        self.sa_property = self._get_sa_property()
        self._translate = translate
        self.renderer = get_renderer(self, translate)
        self._errors = []
        self._warnings = []
        self.value = ""
        self.previous_value = None
        """Value as string of the field. Will be set on rendering the
        form"""

    def __getattr__(self, name):
        """Make attributes from the configuration directly available"""
        return getattr(self._config, name)

    def _get_sa_mapped_class(self):
        # TODO: Raise Exception if this field is not a relation. (None)
        # <2013-07-25 07:44>
        return self.sa_property.mapper.class_

    def _get_sa_property(self):
        if not self._form._item:
            return None
        mapper = sa.orm.object_mapper(self._form._item)
        for prop in mapper.iterate_properties:
            if prop.key == self.name:
                return prop

    def get_type(self):
        """Returns the datatype of the field."""
        if self._config.type:
            return self._config.type
        if self.sa_property:
            try:
                column = self.sa_property.columns[0]
                dtype = str(column.type)
                if dtype in ["VARCHAR", "TEXT"]:
                    return "string"
                elif dtype == "DATE":
                    return "date"
                elif dtype == "INTEGER":
                    return "integer"
                elif dtype == "BOOLEAN":
                    return "boolean"
                else:
                    log.warning('Unhandled datatype: %s' % dtype)
            except AttributeError:
                return self.sa_property.direction.name.lower()
        return "string"

    def get_rules(self):
        """Returns a list of configured rules for the field."""
        return self.rules

    def set_value(self, value):
        self.value = value

    def set_previous_value(self, value):
        self.previous_value = value

    def get_value(self, default=None, expand=False):
        return self._get_value(self.value, default, expand)

    def get_previous_value(self, default=None, expand=False):
        return self._get_value(self.previous_value, default, expand)

    def _get_value(self, value, default, expand):
        if expand:
            if not isinstance(value, list):
                value = [value]
            ex_values = []
            options = self.get_options()
            for opt in options:
                for v in value:
                    if str(v) == str(opt[1]):
                        ex_values.append("%s" % opt[0])
            return ", ".join(ex_values)
        else:
            if value:
                return value
            elif default:
                return default
            else:
                return value

    def get_options(self):
        user_defined_options = self._config.options
        if user_defined_options:
            return user_defined_options
        elif self._form._dbsession:
            # Get mapped clazz for the field
            options = []
            if self.get_type() == 'manytoone':
                options.append(("None", ""))
            clazz = self._get_sa_mapped_class()
            items = self._form._dbsession.query(clazz)
            options.extend([(item, item.id) for item in items])
            return options
        else:
            # TODO: Try to get the session from the item. Ther must be
            # somewhere the already bound session. (torsten) <2013-07-23 00:27>
            log.warning('No db connection configured for this form. Can '
                        'not load options')
            return []

    def add_error(self, error):
        self._errors.append(error)

    def add_warning(self, warning):
        self._warnings.append(warning)

    def get_errors(self):
        return self._errors

    def get_warnings(self):
        return self._warnings

    def render(self):
        """Returns the rendererd HTML for the field"""
        return self.renderer.render()

    def is_relation(self):
        return isinstance(self.sa_property,
                          sa.orm.RelationshipProperty)

    def is_desired(self):
        """Returns true if field is set as desired in field configuration"""
        return self.desired

    def is_required(self):
        """Returns true if either the required flag of the field
        configuration is set or the field is required in the underlying
        datamodel"""
        req = False
        if isinstance(self.sa_property, sa.orm.RelationshipProperty) is False \
           and self.sa_property:
            req = (self.sa_property.columns[0].nullable is False)
        return self.required or req

    def is_readonly(self):
        """Returns true if either the readonly flag of the field
        configuration is set or the whole form is marked as readonly"""
        return self.readonly or False
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.