How to use the dispatch.theme.fields.Field function in dispatch

To help you get started, we’ve selected a few dispatch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
if not isinstance(self.label, str):
            raise InvalidField('Label must be a string')

    def validate(self, data):
        """Validates the field data"""
        raise NotSupportedError

    def to_json(self, data):
        """Returns JSON representation of field data"""
        return data

    def prepare_data(self, data):
        """Prepares field data for use in a template"""
        return data

class ModelField(Field):
    """Base class for model fields"""

    def validate(self, data):
        if self.many:
            if not isinstance(data, list) or not all([is_valid_id(id) for id in data]):
                raise InvalidField('Data must be list of integers or UUIDs')
        else:
            if not is_valid_id(data):
                raise InvalidField('Data must be an integer or UUID')

    def get_many(self, ids):
        id_order = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)])
        return self.model.objects \
            .filter(pk__in=ids) \
            .order_by(id_order)
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
if self.min_value is not None and value < self.min_value:
            raise InvalidField('%s must be greater than %d' % (self.label, self.min_value))

        if self.max_value is not None and value > self.max_value:
            raise InvalidField('%s must be less than than %d' % (self.label, self.max_value))

    def prepare_data(self, data):
        if isinstance(data, int):
            return data
        try:
            return int(data, base=10)
        except (ValueError, TypeError):
            return None

class BoolField(Field):
    type = 'bool'

    def validate(self, data):
        if type(data) is not bool:
            raise InvalidField('%s must be boolean' % self.label)

class SelectField(Field):
    type = 'select'

    def __init__(self, label, options=[], required=False):
        self.options = options
        self.valid_options = set(option[0] for option in self.options)

        if required and not self.options:
            raise InvalidField('Empty select fields cannot be required fields')
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
def prepare_data(self, data):
        if isinstance(data, int):
            return data
        try:
            return int(data, base=10)
        except (ValueError, TypeError):
            return None

class BoolField(Field):
    type = 'bool'

    def validate(self, data):
        if type(data) is not bool:
            raise InvalidField('%s must be boolean' % self.label)

class SelectField(Field):
    type = 'select'

    def __init__(self, label, options=[], required=False):
        self.options = options
        self.valid_options = set(option[0] for option in self.options)

        if required and not self.options:
            raise InvalidField('Empty select fields cannot be required fields')

        super(SelectField, self).__init__(label=label, many=False, required=required)

    def validate(self, data):
        if data == '' or data is None:
            if self.required:
                raise InvalidField('%s is required' % self.label)
            return
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
return self.default

    def prepare_data(self, data):
        if not data:
            return self.default

        try:
            if self.many:
                return self.get_many(data)
            else:
                return self.get_single(data)
        except ObjectDoesNotExist:
            return self.default


class CharField(Field):
    type = 'char'

    def validate(self, data):
        if not isinstance(data, str):
            raise InvalidField('%s data must be a string' % self.label)

        if len(data) > 255:
            raise InvalidField('Max length for charfield data is 255')

        if not len(data) and self.required:
            raise InvalidField('%s is required' % self.label)

class TextField(Field):
    type = 'text'

    def validate(self, data):
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
type = 'datetime'

    def validate(self, data):
        if not data or (isinstance(data, str) and not len(data)):
            if self.required:
                raise InvalidField('%s is required' % self.label)
            else:
                return

        if not parse_datetime(data):
            raise InvalidField('%s must be valid format' % self.label)

    def prepare_data(self, data):
        return parse_datetime(data) if data and isinstance(data, str) else None

class IntegerField(Field):
    type = 'integer'

    def __init__(self, label, many=False, min_value=None, max_value=None, required=False):
        self.min_value = min_value
        self.max_value = max_value

        if min_value is not None and max_value is not None:
            if min_value > max_value:
                raise InvalidField('IntegerField: min_value must be less than max_value')

        super(IntegerField, self).__init__(label=label, many=many, required=required)

    def validate(self, data):
        if not data or (isinstance(data, str) and not len(data)):
            if self.required:
                raise InvalidField('%s is required')
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
raise InvalidField('Max length for charfield data is 255')

        if not len(data) and self.required:
            raise InvalidField('%s is required' % self.label)

class TextField(Field):
    type = 'text'

    def validate(self, data):
        if not isinstance(data, str):
            raise InvalidField('%s data must be a string' % self.label)

        if not len(data) and self.required:
            raise InvalidField('%s is required' % self.label)

class DateTimeField(Field):
    type = 'datetime'

    def validate(self, data):
        if not data or (isinstance(data, str) and not len(data)):
            if self.required:
                raise InvalidField('%s is required' % self.label)
            else:
                return

        if not parse_datetime(data):
            raise InvalidField('%s must be valid format' % self.label)

    def prepare_data(self, data):
        return parse_datetime(data) if data and isinstance(data, str) else None

class IntegerField(Field):
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
widget.set_data(data['data'])
        return widget

class InstructionField(Field):
    type = 'instruction'

    def __init__(self, label, options=[], required=False):
        self.options = options
        self.valid_options = set(option[0] for option in self.options)

        super(InstructionField, self).__init__(label=label, many=False, required=required)

    def validate(self, data):
        pass

class InteractiveMapField(Field):
    type = 'interactive_map'

    # def __init__(self, label):
    #     self.data = {}
    #     self.data['styleCounter'] = 0
    #     self.data['filename'] = None
    #     self.data['elems'] = []
    #     self.data['infos'] = []
    #     self.data['initScript'] = '''
    #       
          
    #       <style>
    #       .c-map-modal-body {
    #           background-color: #ffffff;
    #           margin: 15% auto;
    #           padding: 20px;</style>
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
def __init__(self, label, many=False, required=False):
        self.label = label
        self.many = many
        self.required = required

        if self.many:
            self.default = []
        else:
            self.default = None

        self._creation_counter = Field._creation_counter
        Field._creation_counter += 1

        if not isinstance(self.label, str):
            raise InvalidField('Label must be a string')
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
model = Image
    serializer = ImageSerializer

class PollField(ModelField):
    type = 'poll'

    model = Poll
    serializer = PollSerializer

class PodcastField(ModelField):
    type = 'podcast'

    model = PodcastEpisode
    serializer = PodcastEpisodeSerializer

class WidgetField(Field):
    type = 'widget'

    def __init__(self, label, widgets, required=False):
        super(WidgetField, self).__init__(label, required=required)
        self.widgets = {}

        for widget in widgets:
            self.widgets[widget.id] = WidgetSerializer(widget).data

    def validate(self, data):
        if not data and self.required:
            raise InvalidField('Widget must be selected')

        if not data['id']:
            raise InvalidField("Must specify a widget id")
github ubyssey / dispatch / dispatch / theme / fields.py View on Github external
def prepare_fields():

            def get_field(name, field):
                field.name = name
                return field

            fields = [f for f in list(classdict.items()) if f[0] != 'fields' and isinstance(f[1], Field)]
            fields.sort(key=lambda f: f[1]._creation_counter)

            return [get_field(name, field) for name, field in fields]