def get_changed_fields(serializer, validated_data=None):
    validated_data = validated_data or serializer.validated_data
    result = {}

    orig = get_original_representation(serializer)

    for field_name, field in serializer.fields.items():
        if field.read_only or field.write_only:
            continue

        source = unicode(field.source)

        if source not in validated_data:
            continue

        old_value = orig[field_name] if field_name in orig else None

        value = validated_data[source]
        new_value = field.to_representation(value)

        # TODO: Move this to .to_representation()?
        if isinstance(old_value, six.string_types):
            old_value = strings.normalize_string(old_value)

        if old_value != new_value:
            result[field_name] = FieldChange(field,
                                             old_value,
                                             new_value,
                                             value)

    return result
    def test_normalize_string(self):
        value_pairs = (
            ('  HELLO\r\nWORLD  ', 'HELLO\nWORLD'),
            ('  HELLO\n\rWORLD  ', 'HELLO\n\nWORLD'),
        )

        for value, expected in value_pairs:
            actual = strings.normalize_string(value)
            self.assertEqual(expected, actual)
示例#3
0
def to_string_representation(field, value):
    if hasattr(field, 'to_string_representation'):
        return field.to_string_representation(value)

    if isinstance(field, relations.ManyRelatedField):
        if value is None:
            value = []

        return unicode(list_separator).join([
            to_string_representation(field.child_relation, val)
            for val in value
        ])

    if value is None:
        value = ''

    return strings.normalize_string(unicode(value))
    def normalize_row_data(self, row_data):
        """
        Converts all values in row_data dict to strings.
        Required for Excel imports.
        """
        data = {}
        for key, value in row_data.items():
            if value is None:
                value = ''

            if isinstance(value, float) and value.is_integer():
                value = int(value)

            if not isinstance(value, string_types):
                value = unicode(value)

            data[key] = strings.normalize_string(value)
        return data
示例#5
0
 def pre_read(self, file_object):
     file_object = self.ensure_unicode(file_object)
     file_object = strings.normalize_string(file_object)
     return file_object