Python rest_framework.fields.empty() Examples
The following are 26
code examples of rest_framework.fields.empty().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.fields
, or try the search function
.
Example #1
Source File: metadata.py From dynamic-rest with MIT License | 7 votes |
def get_field_info(self, field): """Adds `related_to` and `nullable` to the metadata response.""" field_info = OrderedDict() for attr in ('required', 'read_only', 'default', 'label'): field_info[attr] = getattr(field, attr) if field_info['default'] is empty: field_info['default'] = None if hasattr(field, 'immutable'): field_info['immutable'] = field.immutable field_info['nullable'] = field.allow_null if hasattr(field, 'choices'): field_info['choices'] = [ { 'value': choice_value, 'display_name': force_text(choice_name, strings_only=True) } for choice_value, choice_name in field.choices.items() ] many = False if isinstance(field, DynamicRelationField): field = field.serializer if isinstance(field, ListSerializer): field = field.child many = True if isinstance(field, ModelSerializer): type = 'many' if many else 'one' field_info['related_to'] = field.get_plural_name() else: type = self.label_lookup[field] field_info['type'] = type return field_info
Example #2
Source File: fields.py From drf-mongo-filters with GNU General Public License v2.0 | 6 votes |
def get_value(self, data): if isinstance(data, MultiValueDict): regex = re.compile(r"^%s\.(.*)$" % re.escape(self.field_name)) ret = {} for name, value in data.items(): match = regex.match(name) if not match: continue key = match.groups()[0] if value != '': ret[key] = value elif isinstance(data, dict): ret = data.get(self.field_name, fields.empty) else: raise ValidationError("not a dict: " + str(type(data))) if ret is fields.empty or len(ret) == 0: return fields.empty return ret
Example #3
Source File: base.py From resolwe with Apache License 2.0 | 6 votes |
def __init__(self, instance=None, data=empty, **kwargs): """Initialize attributes.""" if ( instance is not None and data is not empty and hasattr(self.Meta, "update_protected_fields") ): for field in self.Meta.update_protected_fields: if field in data: data.pop(field) # prevent modification if there are no updates if set(data.keys()).issubset(set(self.Meta.read_only_fields)): raise NoContentError() super().__init__(instance, data, **kwargs)
Example #4
Source File: fields.py From django-rest-framework-mongoengine with MIT License | 6 votes |
def to_internal_value(self, data): """ Dicts of native values <- Dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_dict(data) if not isinstance(data, dict): self.fail('not_a_dict', input_type=type(data).__name__) if not self.allow_empty and len(data.keys()) == 0: message = self.error_messages['empty'] raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }) return { str(key): self.child.run_validation(value) for key, value in data.items() }
Example #5
Source File: mixins.py From django-restql with MIT License | 6 votes |
def to_internal_value(self, data): validated_data = super().to_internal_value(data) if self.partial: empty_fields = [] restql_nested_fields = self.restql_source_field_map.keys() for field in restql_nested_fields: if field in validated_data and validated_data[field] == empty: empty_fields.append(field) for field in empty_fields: # Ignore empty fields for partial update validated_data.pop(field) return validated_data
Example #6
Source File: __init__.py From drf-fast-serializer with MIT License | 5 votes |
def repr_fields(self): return [field for field in self.fields.values() if (not field.read_only) or (field.default is not empty)]
Example #7
Source File: serializers.py From drf-haystack with MIT License | 5 votes |
def __init__(self, instance=None, data=empty, **kwargs): super(HaystackSerializer, self).__init__(instance, data, **kwargs) if not self.Meta.index_classes and not self.Meta.serializers: raise ImproperlyConfigured("You must set either the 'index_classes' or 'serializers' " "attribute on the serializer Meta class.") if not self.instance: self.instance = EmptySearchQuerySet()
Example #8
Source File: get_field_dict.py From drf-schema-adapter with MIT License | 5 votes |
def update_default_from_serializer(self, rv, field_instance): if field_instance.default == empty: return rv['default'] = field_instance.default
Example #9
Source File: decorators.py From drf-typed-views with MIT License | 5 votes |
def build_explicit_param( param: inspect.Parameter, request: Request, settings: ParamSettings, path_args: dict ): if settings.param_type == "path": key = settings.source or param.name raw_value = path_args.get(key, empty) return PathParam(param, request, settings=settings, raw_value=raw_value) elif settings.param_type == "body": return BodyParam(param, request, settings=settings) elif settings.param_type == "header": return HeaderParam(param, request, settings=settings) elif settings.param_type == "current_user": return CurrentUserParam(param, request, settings=settings) elif settings.param_type == "query_param": return QueryParam(param, request, settings=settings)
Example #10
Source File: params.py From drf-typed-views with MIT License | 5 votes |
def _get_raw_value(self): if self.settings.source in ("*", None): return self.request.data return get_nested_value(self.request.data, self.settings.source, fallback=empty)
Example #11
Source File: params.py From drf-typed-views with MIT License | 5 votes |
def _get_raw_value(self): if self.settings.source == "*": raw = self.request.query_params.dict() else: key = self.settings.source or self.param.name raw = self.request.query_params.get(key, empty) raw = empty if raw == "" else raw is_list_type, item_type = parse_list_annotation(self.param.annotation) if raw is not empty and is_list_type: raw = raw.split(self.settings.delimiter) return raw
Example #12
Source File: params.py From drf-typed-views with MIT License | 5 votes |
def __init__( self, param: inspect.Parameter, request: Request, settings: ParamSettings, raw_value: Any = empty, ): self.param = param self.request = request self.settings = settings self.raw_value = raw_value
Example #13
Source File: test_params.py From drf-typed-views with MIT License | 5 votes |
def test_body_raw_value_should_be_empty_when_src_specified_but_not_found(self): body_param = BodyParam( MagicMock(), self.fake_request(data={"a": "b"}), ParamSettings(source="c") ) self.assertEqual(body_param._get_raw_value(), empty)
Example #14
Source File: fields.py From django-rest-framework-mongoengine with MIT License | 5 votes |
def run_validation(self, data=empty): # We force empty strings to None values for relational fields. if data == '': data = None return super(ReferenceField, self).run_validation(data)
Example #15
Source File: renderers_serializers.py From product-definition-center with MIT License | 5 votes |
def _get_default_value(serializer, field_name, field): """ Try to get default value for a field and format it nicely. """ value = field.default if hasattr(value, 'doc_format'): return _get_type_from_docstring(value.doc_format) if value == fields.empty: # Try to get default from model field. try: default = serializer.Meta.model._meta.get_field(field_name).default return default if default != NOT_PROVIDED else None except (FieldDoesNotExist, AttributeError): return None return value
Example #16
Source File: serializers.py From product-definition-center with MIT License | 5 votes |
def get_value(self, data): result = super(StrictManyRelatedField, self).get_value(data) if not result: raise serializers.ValidationError( {self.field_name: [self.error_messages['null']]} ) if result != fields.empty and not isinstance(result, list): raise serializers.ValidationError({self.field_name: ['Expected a list.']}) return result
Example #17
Source File: serializers.py From django-rest-polymorphic with MIT License | 5 votes |
def run_validation(self, data=empty): resource_type = self._get_resource_type_from_mapping(data) serializer = self._get_serializer_from_resource_type(resource_type) validated_data = serializer.run_validation(data) validated_data[self.resource_type_field_name] = resource_type return validated_data # -------------- # Implementation
Example #18
Source File: permission.py From kpi with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, instance=None, data=empty, **kwargs): # Init dicts for later purpose (see below) self.__implied_permissions = {} self.__contradictory_permissions = {} super().__init__(instance=instance, data=data, **kwargs) self.__asset_key = self.__get_key(Asset._meta.app_label, Asset._meta.model_name) self.__collection_key = self.__get_key(Collection._meta.app_label, Collection._meta.model_name) # Prepare dicts for later purpose # (i.e. `get_implied` & `get_contradictory`) self.__init_implied_permissions() self.__init_contradictory_permissions()
Example #19
Source File: initialize.py From cmdb with GNU Lesser General Public License v3.0 | 5 votes |
def empty_none(self, val): if(val == ""): return None return val # def remove_empty_str(data): # for k, v in data.items(): # if v == "": # data.pop(k) # def serializer_init(self, instance=None, data=empty, **kwargs): # if data is not empty: # for k,v in data.items(): # if(v==""): # data.pop(k) # super(Serializer, self).__init__(instance, data, **kwargs)
Example #20
Source File: serializers.py From volontulo with MIT License | 5 votes |
def run_validation(self, data=empty): data = super().run_validation(data) validate_password(data) return data
Example #21
Source File: serializers.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, instance=None, data=empty, **kwargs): """Initialize the Provider Serializer. Here we ensure we use the appropriate serializer to validate the authentication and billing_source parameters. """ super().__init__(instance, data, **kwargs) provider_type = None if data and data != empty: provider_type = data.get("type") if provider_type and provider_type.lower() not in LCASE_PROVIDER_CHOICE_LIST: key = "type" message = f"{provider_type} is not a valid source type." raise serializers.ValidationError(error_obj(key, message)) if provider_type: provider_type = provider_type.lower() self.fields["authentication"] = AUTHENTICATION_SERIALIZERS.get( Provider.PROVIDER_CASE_MAPPING.get(provider_type) )() self.fields["billing_source"] = BILLING_SOURCE_SERIALIZERS.get( Provider.PROVIDER_CASE_MAPPING.get(provider_type) )(default={"bucket": "", "data_source": {"bucket": ""}}) else: self.fields["authentication"] = ProviderAuthenticationSerializer() self.fields["billing_source"] = ProviderBillingSourceSerializer()
Example #22
Source File: contributor.py From resolwe with Apache License 2.0 | 5 votes |
def __init__(self, instance=None, data=empty, **kwargs): """Initialize attributes.""" # Use the correct User model. if self.Meta.model is None: self.Meta.model = auth.get_user_model() super().__init__(instance, data, **kwargs)
Example #23
Source File: fields.py From drf-mongo-filters with GNU General Public License v2.0 | 5 votes |
def get_value(self, data): if isinstance(data, MultiValueDict): ret = data.getlist(self.field_name, fields.empty) elif isinstance(data, dict): ret = data.get(self.field_name, fields.empty) else: raise ValidationError("not a dict: " + str(type(data))) if ret == ['']: ret = fields.empty return ret
Example #24
Source File: filters.py From drf-mongo-filters with GNU General Public License v2.0 | 5 votes |
def parse_value(self, querydict): """ extract value extarct value from querydict and convert it to native missing and empty values result to None """ value = self.field.get_value(querydict) if value in (None, fields.empty, ''): return None return self.field.to_internal_value(value)
Example #25
Source File: field.py From py2swagger with MIT License | 5 votes |
def _get_default_value(self): """ :return: default value for field :rtype: any """ default_value = getattr(self._field, 'default', None) if default_value == fields.empty: default_value = None if hasattr(default_value, '__call__'): default_value = default_value() return default_value
Example #26
Source File: mixins.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 4 votes |
def get_fields_data(self): fields = OrderedDict() serializer_class = self.options_serializer or self.get_serializer_class() try: instance = self.get_object() except: instance = None serializer = serializer_class(instance) model = serializer.Meta.model for field_code, field_class in serializer.get_fields().items(): field_type = field_class.__class__.__name__ fields[field_code] = {'field_type': field_type, 'ui_element': self.get_ui_element(field_code, field_class)} for field_attr_name in self.default_field_attrs: field_attr_value = getattr(field_class, field_attr_name, None) if callable(field_attr_value): if field_attr_value == EMPTY: field_attr_value = '' else: try: # try to get value from callable, without args/kwargs field_attr_value = field_attr_value() except: field_attr_value = str(field_attr_value) fields[field_code][field_attr_name] = field_attr_value # set default values from a model data fields[field_code]['default'] = None if field_type not in self.default_always_null_fields: try: default_value = model._meta.get_field(field_code).default if default_value != NOT_PROVIDED: if callable(default_value): default_value = default_value() try: json.dumps(default_value) except: default_value = str(default_value) fields[field_code]['default'] = default_value except: pass if instance: instance_data = serializer_class(instance, many=False).data for field_name, field_data in fields.items(): field_data['value'] = instance_data.get(field_name) return fields