class WritableField

from rest_framework.fields import WritableField
Documentation Source code
    Base for read/write fields.
    

Ancestors (MRO)

  1. WritableField
  2. Field

Attributes

  Defined in
creation_counter = 3 Field
default = None WritableField
default_error_messages = {u'invalid': <django.utils.functional.__proxy__ object at 0x7f5efc8d53d0>, u'required': <django.utils.functional.__proxy__ object at 0x7f5efc8d5390>} WritableField
default_validators = [] WritableField
empty = Field
errors = <property object at 0x7f5efc8cf470> Field
form_field_class = <class 'django.forms.fields.CharField'> Field
partial = False Field
read_only = True Field
type_label = field Field
type_name = None Field
use_files = False Field
widget = <class 'django.forms.widgets.TextInput'> WritableField
widget = None Field
write_only = False WritableField
Expand Collapse

Methods

def attributes(self): Field

        Returns a dictionary of attributes to be used when serializing to xml.
        
    def attributes(self):
        """
        Returns a dictionary of attributes to be used when serializing to xml.
        """
        if self.type_name:
            return {'type': self.type_name}
        return {}

def field_from_native(self, data, files, field_name, into):

WritableField

        Given a dictionary and a field name, updates the dictionary `into`,
        with the field and it's deserialized value.
        
    def field_from_native(self, data, files, field_name, into):
        """
        Given a dictionary and a field name, updates the dictionary `into`,
        with the field and it's deserialized value.
        """
        if self.read_only:
            return

        try:
            data = data or {}
            if self.use_files:
                files = files or {}
                try:
                    native = files[field_name]
                except KeyError:
                    native = data[field_name]
            else:
                native = data[field_name]
        except KeyError:
            if self.default is not None and not self.partial:
                # Note: partial updates shouldn't set defaults
                native = self.get_default_value()
            else:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                return

        value = self.from_native(native)
        if self.source == '*':
            if value:
                into.update(value)
        else:
            self.validate(value)
            self.run_validators(value)
            into[self.source or field_name] = value

Field

        Given a dictionary and a field name, updates the dictionary `into`,
        with the field and it's deserialized value.
        
    def field_from_native(self, data, files, field_name, into):
        """
        Given a dictionary and a field name, updates the dictionary `into`,
        with the field and it's deserialized value.
        """
        return

def field_to_native(self, obj, field_name):

WritableField

    def field_to_native(self, obj, field_name):
        if self.write_only:
            return None
        return super(WritableField, self).field_to_native(obj, field_name)

Field

        Given and object and a field name, returns the value that should be
        serialized for that field.
        
    def field_to_native(self, obj, field_name):
        """
        Given and object and a field name, returns the value that should be
        serialized for that field.
        """
        if obj is None:
            return self.empty

        if self.source == '*':
            return self.to_native(obj)

        source = self.source or field_name
        value = obj

        for component in source.split('.'):
            value = get_component(value, component)
            if value is None:
                break

        return self.to_native(value)

def from_native(self, value): WritableField

        Reverts a simple representation back to the field's value.
        
    def from_native(self, value):
        """
        Reverts a simple representation back to the field's value.
        """
        return value

def get_default_value(self): WritableField

    def get_default_value(self):
        if is_simple_callable(self.default):
            return self.default()
        return self.default

def initialize(self, parent, field_name): Field

        Called to set up a field prior to field_to_native or field_from_native.

        parent - The parent serializer.
        field_name - The name of the field being initialized.
        
    def initialize(self, parent, field_name):
        """
        Called to set up a field prior to field_to_native or field_from_native.

        parent - The parent serializer.
        field_name - The name of the field being initialized.
        """
        self.parent = parent
        self.root = parent.root or parent
        self.context = self.root.context
        self.partial = self.root.partial
        if self.partial:
            self.required = False

def label_tag(self): Field

    def label_tag(self):
        return '<label for="%s">%s:</label>' % (self._name, self.label)

def metadata(self): Field

    def metadata(self):
        metadata = SortedDict()
        metadata['type'] = self.type_label
        metadata['required'] = getattr(self, 'required', False)
        optional_attrs = ['read_only', 'label', 'help_text',
                          'min_length', 'max_length']
        for attr in optional_attrs:
            value = getattr(self, attr, None)
            if value is not None and value != '':
                metadata[attr] = force_text(value, strings_only=True)
        return metadata

def run_validators(self, value): WritableField

    def run_validators(self, value):
        if value in validators.EMPTY_VALUES:
            return
        errors = []
        for v in self.validators:
            try:
                v(value)
            except ValidationError as e:
                if hasattr(e, 'code') and e.code in self.error_messages:
                    message = self.error_messages[e.code]
                    if e.params:
                        message = message % e.params
                    errors.append(message)
                else:
                    errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)

def to_native(self, value): Field

        Converts the field's value into it's simple representation.
        
    def to_native(self, value):
        """
        Converts the field's value into it's simple representation.
        """
        if is_simple_callable(value):
            value = value()

        if is_protected_type(value):
            return value
        elif (is_non_str_iterable(value) and
              not isinstance(value, (dict, six.string_types))):
            return [self.to_native(item) for item in value]
        elif isinstance(value, dict):
            # Make sure we preserve field ordering, if it exists
            ret = SortedDict()
            for key, val in value.items():
                ret[key] = self.to_native(val)
            return ret
        return force_text(value)

def validate(self, value): WritableField

    def validate(self, value):
        if value in validators.EMPTY_VALUES and self.required:
            raise ValidationError(self.error_messages['required'])

def widget_html(self): Field

    def widget_html(self):
        if not self.widget:
            return ''

        attrs = {}
        if 'id' not in self.widget.attrs:
            attrs['id'] = self._name

        return self.widget.render(self._name, self._value, attrs=attrs)