def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ ret = OrderedDict() errors = OrderedDict() fields = [ field for field in self.fields.values() if (not field.read_only) or (field.default is not empty) ] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def loop_fields(self, data, errors): fields = self._writable_fields ret = OrderedDict() for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) # ---- start core code ---- get_value_method = getattr(self, 'get_' + field.field_name, None) if get_value_method: primitive_value = get_value_method(field, data) else: primitive_value = field.get_value(data) # ---- end core code ---- try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ ret = OrderedDict() errors = OrderedDict() fields = [ field for field in self.fields.values() if (not field.read_only) or (field.default is not empty) ] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): ret = super().to_internal_value(data) set_value(ret, ['type_'], data['type_']) if data['type_'] == 'campaign': set_value(ret, ['campaign'], data['campaign']) return ret
def field_to_internal_value(self, field, data): ret = OrderedDict() errors = OrderedDict() validate_method = getattr( self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, Mapping): message = self.error_messages["invalid"].format(datatype=type(data).__name__) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [message]}, code="invalid") ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, "validate_" + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: self.error_list.update(errors) # Raise a CustomValidationErrors with the list of ValidationErrors raise CustomValidationErrors(error_list=errors) return ret
def transform(self, data, request, obj, forwards): method_prefix = 'forwards_' if forwards else 'backwards_' kwargs = { 'data': data, 'request': request } if not forwards: kwargs['obj'] = obj if self.for_field: return getattr(self, method_prefix + 'field')( **kwargs ) elif self.for_serializer: return getattr(self, method_prefix + 'serializer')( **kwargs ) else: if forwards: value = self.field.get_value(data) else: value = self.field.get_attribute(obj) kwargs['data'] = data[self.field] transformed_value = getattr(self, method_prefix + 'specific_field')( obj=obj, data=value, request=request ) if forwards: set_value(data, self.field.source_attrs, value) else: data[self.field.field_name] = transformed_value return data
def to_internal_value(self, data): if not isinstance(data, dict): message = self.error_messages["invalid"].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }) ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, "validate_" + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) return ret, errors
def to_internal_value(self, data): """ Overrides the default deserialization to look up related objects that are needed to create/update the correct models. """ out_data = { 'program': self.root.instance, 'course_code': self._get_course_code(data) } # pylint: disable=no-member # handle run_modes if present if 'run_modes' in data: # NB this next block is based on `ModelSerializer.to_internal_value` # but has to be duplicated here because the superclass' method is # incompatible with nested writes. errors = {} try: validated_value = self.fields['run_modes'].run_validation( data['run_modes']) except exceptions.ValidationError as exc: errors['run_modes'] = exc.detail else: fields.set_value(out_data, self.fields['run_modes'].source_attrs, validated_value) if errors: raise exceptions.ValidationError(errors) return out_data
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ from rest_framework.fields import get_error_detail, set_value from collections import OrderedDict from django.core.exceptions import ValidationError as DjangoValidationError if not isinstance(data, Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='invalid') ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: # ManyRelatedField 取消写入数据验证, 防止每次都去查询数据库 if isinstance(field, ManyRelatedField) and isinstance( field.child_relation, PrimaryKeyRelatedField ) and primitive_value is not empty: if not isinstance(primitive_value, (list, tuple)): raise ValidationError() validated_value = [int(i) for i in primitive_value] else: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__) raise drf_fields.ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [message]}) ret = OrderedDict() errors = OrderedDict() if data['_cls']: cls = get_document(data['_cls']) if not issubclass(cls, self.Meta.model): #not playing the 'pass anything in, and we'll construct it for you' game cls = self.Meta.model else: cls = self.Meta.model fields = self.chainmap[cls] fields = [ field for name, field in fields.items() if not field.read_only ] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except drf_fields.ValidationError as exc: errors[field.field_name] = exc.detail except drf_fields.DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: drf_fields.set_value(ret, field.source_attrs, validated_value) if errors: raise drf_fields.ValidationError(errors) return ret
def to_internal_value(self, data): ret = super(NestedModelSerializer, self).to_internal_value(data) # So, in the case that this object is nested, we really really need the id. if getattr(self, 'parent', None): child_model = self.Meta.model pk_field_name = child_model._meta.pk.name pk_field = self.fields[pk_field_name] primitive_value = pk_field.get_value(data) set_value(ret, pk_field.source_attrs, primitive_value) errors = OrderedDict() return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise drf_fields.ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }) ret = OrderedDict() errors = OrderedDict() if data['_cls']: cls = get_document(data['_cls']) if not issubclass(cls, self.Meta.model): #not playing the 'pass anything in, and we'll construct it for you' game cls = self.Meta.model else: cls = self.Meta.model fields = self.chainmap[cls] fields = [field for name, field in fields.items() if not field.read_only] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except drf_fields.ValidationError as exc: errors[field.field_name] = exc.detail except drf_fields.DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: drf_fields.set_value(ret, field.source_attrs, validated_value) if errors: raise drf_fields.ValidationError(errors) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. After calling super, we handle dynamic data which is not handled by super class """ ret = super(DocumentSerializer, self).to_internal_value(data) [drf_fields.set_value(ret, [k], data[k]) for k in data if k not in ret] return ret
def to_internal_value(self, data): """Verbatim copy of the original drf `to_internal_value()` method. This method replicates the implementation found on `restframework.serializers.Serializer.to_internal_value` method because the dynamic-rest package (which we are using, and which overrides the base implementation) adds some custom stuff on top of it which depends on the input data containing the instance's `id` property, which we are not requiring. A HarvestableResource's `id` is an implementation detail that is not exposed publicly. We rely on the instance's `unique_identifier` instead. """ if not isinstance(data, typing.Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise exceptions.ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='invalid') ret = collections.OrderedDict() errors = collections.OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, f"validate_{field.field_name}", None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except exceptions.ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise exceptions.ValidationError(errors) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='invalid') ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) field_name = field.field_name field_data = data.get(field_name) if field_name == 'address': primitive_value = json.loads(field_data) elif field_name == 'photo' and isinstance(field_data, str): continue elif field_name == 'owner' and field_data is None: primitive_value = User.objects.get(is_admin=True).id else: primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field_name] = exc.detail except DjangoValidationError as exc: errors[field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): try: ret = super(NestedModelSerializer, self).to_internal_value(data) except AssertionError: raise ValidationError({self.__class__.__name__: "Cannot descend and create nested objects."}) # So, in the case that this object is nested, we really really need the id. if getattr(self, 'parent', None): child_model = self.Meta.model pk_field_name = child_model._meta.pk.name pk_field = self.fields[pk_field_name] primitive_value = pk_field.get_value(data) set_value(ret, pk_field.source_attrs, primitive_value) errors = OrderedDict() return ret
def to_internal_value(self, data): if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }) def append_error(field, key, error): if errors.get(field, None) is None: errors[field] = dict() errors[field][key] = error ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: code = getattr(exc, 'code', None) if code is not None: append_error(field.field_name, code, ' '.join(exc.detail)) else: errors[field.field_name] = ' '.join(exc.detail) except DjangoValidationError as exc: errors[field.field_name] = ' '.join(exc.messages) except serializers.SkipField: pass else: rest_fields.set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='invalid') data['attributes'] = [] # resource_id = data['id'] ret = OrderedDict() ret['type'] = self.resourceDefined errors = OrderedDict() fields = self._writable_fields for k, v in self.attr_map.items(): data['attributes'].append({ 'value': data.get(k, None), 'attributeDefined': v[0], 'resourcetype': v[1] }) for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): """ In order to be able to handle passing tag_name in array, we need to overwrite this method to bypass run_validation for tags """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }) ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: if field.field_name != 'tags': validated_value = field.run_validation(primitive_value) else: validated_value = primitive_value if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='invalid') ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: if field.field_name == 'company': continue validate_method = getattr( self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): try: ret = super(NestedModelSerializer, self).to_internal_value(data) except AssertionError: raise ValidationError({ self.__class__.__name__: "Cannot descend and create nested objects." }) # So, in the case that this object is nested, we really really need the id. if getattr(self, 'parent', None): child_model = self.Meta.model pk_field_name = child_model._meta.pk.name pk_field = self.fields[pk_field_name] primitive_value = pk_field.get_value(data) set_value(ret, pk_field.source_attrs, primitive_value) errors = OrderedDict() return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }) ret = OrderedDict() errors = OrderedDict() fields = [ field for field in self.fields.values() if (not field.read_only) or (field.default is not empty) ] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[unicode(field.label)] = exc.detail except DjangoValidationError as exc: errors[unicode(field.label)] = list(exc.messages) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value_fields(self, data, fields=None): """ This is basically a copy of the super.to_internal_value(), but we need the option to only use certain fields. """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }) validated_values = OrderedDict() errors = OrderedDict() fields = fields or [ field for field in self.fields.values() if (not field.read_only) or (field.default is not empty) ] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: set_value(validated_values, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return validated_values
def to_internal_value_fields(self, data, fields=None): """ This is basically a copy of the super.to_internal_value(), but we need the option to only use certain fields. """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [message]}) validated_values = OrderedDict() errors = OrderedDict() fields = fields or [ field for field in self.fields.values() if (not field.read_only) or (field.default is not empty) ] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: set_value(validated_values, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return validated_values
def to_internal_value(self, data): ret = OrderedDict() errors = OrderedDict() for field in tenant_specific_fields_definitions: validators = [] for validator_instance in field.validators.all(): validator_function = import_from_string( validator_instance.module_path) validators.append(validator_function) validate_method = compose_list(validators) primitive_value = self.fields.get(field.name).get_value(data) try: validated_value = self.fields.get( field.name).run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except serializers.ValidationError as exc: errors[field.name] = exc.detail except DjangoValidationError as exc: errors[field.name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, self.fields.get(field.name).source_attrs, validated_value) if errors: raise serializers.ValidationError(errors) data.update(dict(ret)) ret = super(TenantSpecificTableRowSerializer, self).to_internal_value(data) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='invalid') ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def ParseStrFilter(self, _str): ret = dict() str_filter = '' ar_obj = _str.split('=') str_field_name = ar_obj[0].split('[')[0] str_operator = None is_not = False is_or = False if str_field_name[0:4] == 'or__': is_or = True str_field_name = str_field_name[4:] if '[' in ar_obj[0]: str_operator = ar_obj[0].split('[')[1].split(']')[0] if str_operator == "not_in": is_not = True str_operator = "in" str_filter = str_field_name if str_operator != None: str_filter += "__" + str_operator value = ar_obj[1] fields = self._writable_fields for field in fields: if field.field_name == "str_field": set_value(ret, field.source_attrs, str_field_name) elif field.field_name == "str_value": set_value(ret, field.source_attrs, value) elif field.field_name == "str_operator": set_value(ret, field.source_attrs, str_operator) elif field.field_name == "is_not": set_value(ret, field.source_attrs, is_not) elif field.field_name == "is_or": set_value(ret, field.source_attrs, is_or) return ret
def to_internal_value(self, data): """ Overrides the default deserialization to look up related objects that are needed to create/update the correct models. """ out_data = {'program': self.root.instance, 'course_code': self._get_course_code(data)} # pylint: disable=no-member # handle run_modes if present if 'run_modes' in data: # NB this next block is based on `ModelSerializer.to_internal_value` # but has to be duplicated here because the superclass' method is # incompatible with nested writes. errors = {} try: validated_value = self.fields['run_modes'].run_validation(data['run_modes']) except exceptions.ValidationError as exc: errors['run_modes'] = exc.detail else: fields.set_value(out_data, self.fields['run_modes'].source_attrs, validated_value) if errors: raise exceptions.ValidationError(errors) return out_data
def to_internal_value(self, data): logging.info("MedRecordSerializer: To to_internal_value") ret = OrderedDict() errors = OrderedDict() # operator_id required # if not 'operator_id' in data: operator_id = data.get('operator_id', None) if not operator_id: error = "Error: operator_id is required" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) else: # operator_id must be in Staff list operator_id = data.get('operator_id', False) staff_q = Staff.objects.filter(mis_id=data['mis_id'], mis_staff_id=operator_id) if not staff_q.exists(): error = "Error: operator_id must be in staff list" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['operator_id'] = staff_q.first().id patient_address_src = data.get('patient_address_src', None) if patient_address_src: patient_address_src_qs = AddrDocType.objects.filter(name=patient_address_src) if patient_address_src_qs.exists(): patient_address_src_obj = patient_address_src_qs.first() data['patient_address_src'] = patient_address_src_obj.id else: error = f"Bad patient_address_src: {data['patient_address_src']}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) else: data['patient_address_src'] = 1 # Невідомо noresult = data.get('noresult', None) if noresult: noresult_qs = NoResult.objects.filter(name=noresult) if noresult_qs.exists(): noresult_obj = noresult_qs.first() data['noresult'] = noresult_obj.id else: error = f"Bad noresult: {data['noresult']}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) else: data['noresult'] = 1 # Результативний hospital = data.get('hospital', None) if hospital: data['is_hospital_record'] = True else: data['is_hospital_record'] = False if not self.instance: call_card_id = data.get('call_card_id', False) if not call_card_id: error = "Error: call_card_id is required!" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) else: #call_card_id = data.get('call_card_id', False) call_card_qs = CallCard.objects.filter(call_card_id=call_card_id) if call_card_qs.exists(): call_card_obj = call_card_qs.first() if int(call_card_obj.mis_id.id) != int(data['mis_id']): error = f"CallCard [{data['call_card_id']}] doesnt belong to MIS [{data['mis_id']}]" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['callcard'] = call_card_obj.id if call_card_obj.crew_id: data['crew'] = call_card_obj.crew_id.id else: error = f"MedRecord: No crew in related CallCard {call_card_obj.call_card_id}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) else: error = f"Bad call_card_id: {data['call_card_id']}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = data.get(field.source_attrs[0], False) if primitive_value: try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) #ret = super().to_internal_value(data=data) return ret
def to_internal_value(self, data): logging.info("CrewSerializer: To to_internal_value") ret = OrderedDict() errors = OrderedDict() mis_car_id = data.get('mis_car_id', False) if self.instance == None: if mis_car_id: mis_car_q = Cars.objects.filter(mis_id=data['mis_id'], mis_car_id=mis_car_id) if mis_car_q.exists(): data['car_id'] = mis_car_q.first().id else: error = "CrewSerializer. Crew mis_car_id does not exist" logging.error(error) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [error]}) else: crew_comment = data.get('crew_comment', None) if crew_comment: data['car_id'] = None logging.info(f'CrewSerializer: setting car_id to null') else: error = "CrewSerializer. Crew mis_car_id or crew_comment required" logging.error(error) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [error]}) mis_facility_id = data.get('mis_facility_id', False) if mis_facility_id: facility_q = Facility.objects.filter( mis_id=data['mis_id'], mis_facility_id=mis_facility_id) if facility_q.exists(): data['facility_id'] = facility_q.first().id else: error = "CrewSerializer. Crew mis_facility_id does not exist" logging.error(error) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [error]}) else: if self.instance == None: error = "CrewSerializer. Crew mis_facility_id required" logging.error(error) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [error]}) crew_status = data.get('crew_status', False) if crew_status: if crew_status.isdigit(): data['crew_status'] = crew_status else: q_qs = CrewStatus.objects.filter(crewstatus_name=crew_status) if q_qs.exists(): data['crew_status'] = q_qs.first().id else: error = f"Error: crew_status is unknown: {crew_status}" logging.error(error) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: error}) else: if self.instance == None: data['crew_status'] = None if self.instance == None: ret = super().to_internal_value(data=data) else: fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = data.get(field.source_attrs[0], False) if primitive_value: try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: # print(f'Setting: {field.source_attrs}:{validated_value}') set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_representation(self, instance): ret = super().to_representation(instance) refresh = self.get_token(self.user) set_value(ret, ['refresh'], str(refresh)) set_value(ret, ['access'], str(refresh.access_token)) return ret
def to_internal_value(self, data): """ Monkey patch the validate empty values function of the serializers fields. This way the validation that checks if fields are required also works on partial updates (PATCH) requests. """ def custom_validate_empty_values(self, data): """ The custom validate empty function that always checks for empty values, even on partial update. """ if self.read_only: return (True, self.get_default()) if data is empty: # The partial_update check is removed here. if self.required: self.fail('required') return (True, self.get_default()) if data is None: if not self.allow_null: self.fail('null') return (True, None) return (False, data) if self.root.partial and 'id' not in data: for field in self.fields.values(): # This is the actual monkey patching part. funcType = type(field.validate_empty_values) field.validate_empty_values = funcType(custom_validate_empty_values, field, field.__class__) if isinstance(data, dict) and 'id' in data: # Set the instance so validators work properly try: self.instance = self.Meta.model.objects.get(pk=data.get('id')) except ObjectDoesNotExist: pass if not self.create_only and len(data) == 1: ret = OrderedDict() errors = OrderedDict() field = self.fields['id'] validate_method = getattr(self, 'validate_id', None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret model_cls = self.root.Meta.model instance = self.root.instance content_type = ContentType.objects.get_for_model(model_cls) generic_related_fields = [field.name for field in model_cls._meta.virtual_fields] if self.parent.field_name in generic_related_fields: data['content_type'] = content_type.pk if instance: data['object_id'] = instance.pk else: # Remove unique together validator because we are creating so it's always unique. self.validators = [validator for validator in self.validators if not isinstance(validator, UniqueTogetherValidator)] return super(RelatedSerializerMixin, self).to_internal_value(data)
def to_internal_value(self, data): ret = super(DocumentSerializer, self).to_internal_value(data) [drf_fields.set_value(ret, [k], data[k]) for k in data if k not in ret] return ret
def to_internal_value(self, data): contacts = data.pop('contacts', None) ret = super().to_internal_value(data) set_value(ret, ['contacts'], contacts) return ret
def to_internal_value(self, data): ret = super().to_internal_value(data) if 'groups' in data: set_value(ret, ['groups'], data['groups']) return ret
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__) raise ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [message]}, code='invalid') ret = OrderedDict() errors = OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) if isinstance(primitive_value, str) and isinstance( field, serializers.HyperlinkedRelatedField): # we need this because DRF HyperlinkedRelatedField is not fully compatible with Django 2.0+ # when dealing with spaces in the URL (e.g. when we do lookup by name). # The issue has been reported and reopened, see the description here: # - https://github.com/encode/django-rest-framework/issues/4748 # Once it is resolved there, we won't need this line anymore primitive_value = unquote(primitive_value) try: # For create only if not self.partial and hasattr(self, 'initial_data') and isinstance(primitive_value, dict) \ and 'url' in primitive_value: model_class = field.Meta.model pk = self._get_related_pk(primitive_value, model_class, related_field=field) if pk: obj = model_class.objects.filter(pk=pk, ).first() serializer = self._get_serializer_for_field( field, instance=obj, ) primitive_value = { k: v for k, v in serializer.data.items() } self.initial_data[field.field_name] = primitive_value validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret
def to_internal_value(self, data): logging.info("CallCardSerializer: To to_internal_value") ret = OrderedDict() errors = OrderedDict() if not 'mis_id' in data: mis_obj = Mis.objects.get(mis_user=data['mis_user']) data['mis_id'] = mis_obj.id data['mis_user'] = mis_obj.mis_user.id data['start_datetime'] = data.get('start_datetime', timezone.now().isoformat()) try: instance_start = datetime.fromisoformat(data['start_datetime']) except Exception as ex: logging.error(f"CallCardSerializer:: invalid start_datetime: {data['start_datetime']}") raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [ex]}) data['call_station'] = data.get('call_station', "1") if data['start_datetime'] == "": error = "start_date_time may not be an empty string" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) crew_id = data.get('crew_id', False) if crew_id: crew_q = Crew.objects.filter(mis_id=data['mis_id'], crew_id=data['crew_id']) if crew_q.exists(): crew_obj = crew_q.first() if int(crew_obj.mis_id.id) != int(data['mis_id']): error = f"Crew [{data['crew_id']}] doesnt belong to MIS [{data['mis_id']}]" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['crew_id'] = crew_obj.id else: error = f"Bad mis_id:crew_id: {data['mis_id']}: {data['crew_id']}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) call_station = data.get('call_station', "1") if (type(call_station) == int) or call_station.isdigit(): station_obj = CallStations.objects.get(id=call_station) if station_obj == None: error = f"Bad callStation: {call_station}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['call_station'] = station_obj.id else: station_obj = CallStations.objects.filter(station_name=call_station).first() if station_obj == None: error = f"Bad callStation: {call_station}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['call_station'] = station_obj.id call_priority = data.get('call_priority', False) if call_priority: if (type(call_priority) == int) or call_priority.isdigit(): priority_obj = CallPriority.objects.get(id=call_priority) if priority_obj == None: error = f"Bad call_priority: {call_priority}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['call_priority'] = priority_obj.id else: priority_obj = CallPriority.objects.filter(priority_name=call_priority).first() if priority_obj == None: error = f"Bad call_priority: {call_priority}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['call_priority'] = priority_obj.id call_result = data.get('call_result', False) if call_result: if (type(call_result) == int) or call_result.isdigit(): result_obj = CallResult.objects.get(id=call_result) if result_obj == None: error = f"Bad call_result: {call_result}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['call_result'] = result_obj.id else: result_obj = CallResult.objects.filter(result_name=call_result).first() if result_obj == None: error = f"Bad call_result: {call_result}" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) data['call_result'] = result_obj.id # Comments to CallCard only by Operator103 c_c = data.get('call_comment', None) if c_c: if data['call_station'] != 2: data.pop('call_comment') else: c_c = str(c_c) if len(c_c) > 254: logging.warning("Stripping call_comment") data['call_comment'] = c_c[:254] else: data['call_comment'] = c_c # end_datetime is required end_datetime = data.get('end_datetime', None) if not end_datetime: error = "Error: end_datetime is required" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) # operator_id required operator_id = data.get('operator_id', None) if not operator_id: error = "Error: operator_id is required" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) # operator_id must be in Staff list staff_qs = Staff.objects.filter(mis_id=data['mis_id'], mis_staff_id=operator_id) if not staff_qs.exists(): error = "Error: operator_id must be in staff list" logging.error(error) raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [error]}) # Only Operator103 goes to CallCard operator_id_pk = staff_qs.first().id if data['call_station'] <= 2 | (not self.instance): data['operator_id'] = operator_id_pk else: data.pop('operator_id') # print(f'data[start_datetime]: {data["start_datetime"]}') fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = data.get(field.source_attrs[0], False) if primitive_value: try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) data['operator_id'] = operator_id_pk # Check if already Archive if self.instance and self.instance.call_station: if self.instance.call_station.station_name == "Архів": cc_slug = ret.get('call_card_id', None) logging.warning(f"CallCardSerializer:: The card# {cc_slug} is in Archive already. ") callrecord_start = datetime.fromisoformat(data['start_datetime']) logging.warning(f'callrecord_start : {callrecord_start.isoformat()}') logging.warning(f'callcard_end_time: {self.instance.end_datetime.isoformat()}') # logging.warning("CallCardSerializer:: puting call_station to Archive back") # ret['call_station'] = CallStations.objects.get(station_name="Архів") if callrecord_start < self.instance.end_datetime: logging.warning("CallCardSerializer:: puting call_station to Archive back") ret['call_station'] = CallStations.objects.get(station_name="Архів") #ret = super().to_internal_value(data=data) # print(f'ret [start_datetime]: {ret["start_datetime"]}') # print(ret) return ret