class ProbabilitiesSerializer(serializers.Serializer): priority = serializers.DictField(child=serializers.FloatField()) resolution = serializers.DictField(child=serializers.FloatField()) areas_of_testing = serializers.DictField(child=serializers.FloatField())
class NoLoggedInHomeSerializer(serializers.Serializer): page = serializers.IntegerField() catalogs = serializers.ListField() next_api = serializers.DictField()
class AllFieldsSerializer(serializers.ModelSerializer): field_decimal_uncoerced = serializers.DecimalField( source='field_decimal', max_digits=6, decimal_places=3, coerce_to_string=False ) field_method_float = serializers.SerializerMethodField() def get_field_method_float(self, obj) -> float: return 1.3456 field_method_object = serializers.SerializerMethodField() def get_field_method_object(self, obj) -> dict: return {'key': 'value'} field_regex = serializers.RegexField(r'^[a-zA-z0-9]{10}\-[a-z]') # composite fields field_list = serializers.ListField( child=serializers.FloatField(), min_length=3, max_length=100, ) field_list_serializer = serializers.ListField( child=AuxSerializer(), source='field_list_object', ) # extra related fields field_related_slug = serializers.SlugRelatedField( read_only=True, source='field_foreign', slug_field='id' ) field_related_string = serializers.StringRelatedField( source='field_foreign' ) field_related_hyperlink = serializers.HyperlinkedRelatedField( read_only=True, source='field_foreign', view_name='aux-detail' ) field_identity_hyperlink = serializers.HyperlinkedIdentityField( read_only=True, view_name='allfields-detail' ) # read only - model traversal field_read_only_nav_uuid = serializers.ReadOnlyField(source='field_foreign.id') field_read_only_nav_uuid_3steps = serializers.ReadOnlyField( source='field_foreign.field_foreign.field_foreign.id', allow_null=True, # force field output even if traversal fails ) field_read_only_model_function_basic = serializers.ReadOnlyField(source='model_function_basic') field_read_only_model_function_model = serializers.ReadOnlyField(source='model_function_model.id') # override default writable bool field with readonly field_bool_override = serializers.ReadOnlyField() field_model_property_float = serializers.ReadOnlyField() field_dict_int = serializers.DictField( child=serializers.IntegerField(), source='field_json', ) # there is a JSON model field for django>=3.1 that would be placed automatically. for <=3.1 we # need to set the field explicitly. defined here for both cases to have consistent ordering. field_json = serializers.JSONField() class Meta: fields = '__all__' model = AllFields
class BadRequestResponseSerializer(serializers.Serializer): errors = serializers.DictField()
class VnfInstanceSerializer(serializers.Serializer): id = serializers.CharField(help_text="Identifier of the VNF instance.", max_length=255, required=True, allow_null=False, allow_blank=False) vnfInstanceName = serializers.CharField( help_text="Name of the VNF instance. \ This attribute can be modified with the PATCH method.", max_length=255, required=False, allow_null=True, allow_blank=True) vnfInstanceDescription = serializers.CharField( help_text="Human-readable description of the VNF instance. \ This attribute can be modified with the PATCH method.", required=False, allow_null=True, allow_blank=True) vnfdId = serializers.CharField( help_text="Identifier of the VNFD on which the VNF instance is based.", max_length=255, required=False, allow_null=True, allow_blank=True) vnfProvider = serializers.CharField( help_text="Provider of the VNF and the VNFD. \ The value is copied from the VNFD. ", max_length=255, required=False, allow_null=True, allow_blank=True) vnfProductName = serializers.CharField( help_text="Name to identify the VNF Product. \ The value is copied from the VNFD.", max_length=255, required=False, allow_null=True, allow_blank=True) vnfSoftwareVersion = serializers.CharField( help_text="Software version of the VNF. \ The value is copied from the VNFD.", max_length=255, required=False, allow_null=True, allow_blank=True) vnfdVersion = serializers.CharField( help_text="Identifies the version of the VNFD. \ The value is copied from the VNFD.", max_length=255, required=False, allow_null=True, allow_blank=True) vnfPkgId = serializers.CharField( help_text= "Identifier of information held by the NFVO about the specific VNF package on which the VNF is based. \ This attribute can be modified with the PATCH method.", max_length=255, required=False, allow_null=True, allow_blank=True) vnfConfigurableProperties = serializers.DictField( help_text= "Current values of the configurable properties of the VNF instance. \ Configurable properties referred in this attribute are declared in the VNFD", child=serializers.CharField(help_text="KeyValue Pairs", allow_blank=True), required=False, allow_null=True) vimConnectionInfo = VimConnectionInfoSerializer( help_text= "Information about VIM connections to be used for managing the resources for the VNF instance. \ This attribute can be modified with the PATCH method.", required=False, allow_null=True) instantiationState = serializers.ChoiceField( help_text="The instantiation state of the VNF.", choices=["NOT_INSTANTIATED", "INSTANTIATED"], required=True, allow_null=False, allow_blank=False) instantiatedVnfInfo = InstantiatedVnfInfoSerializer( help_text="Information specific to an instantiated VNF instance. \ This attribute shall be present if the instantiateState attribute value is INSTANTIATED", required=False, allow_null=True) metadata = serializers.DictField( help_text="Additional VNF-specific metadata describing the VNF instance.\ This attribute can be modified with the PATCH method.", child=serializers.CharField(help_text="KeyValue Pairs", allow_blank=True), required=False, allow_null=True) extensions = serializers.DictField( help_text= "VNF-specific attributes that affect the lifecycle management of this VNF instance by the VNFM, or the lifecycle management scripts. \ This attribute can be modified with the PATCH method.", child=serializers.CharField(help_text="KeyValue Pairs", allow_blank=True), required=False, allow_null=True) _links = _LinksSerializer( help_text="Links to resources related to this resource.", required=False, allow_null=False)
class KeyEntrySerializer(serializers.HyperlinkedModelSerializer): """Serializer to present users (get_user_model()).""" class Meta: model = KeyEntry fields = ('__all__') passwords = PasswordSerializer(read_only=True, many=True) passwords_write = serializers.ListField( child=serializers.DictField(child=serializers.CharField()), write_only=True, ) def validate(self, data): # TODO: Lookup using permission system, or something like that # List of users who needs this password # users = [ # user, get_user_model().objects.get(pk=3) # ] users = get_user_model().objects.filter(public_keys__isnull=False) users_set = set([x.pk for x in users]) passwords = data['passwords_write'] passwords_keyset = set([int(x['user_pk']) for x in passwords]) if users_set != passwords_keyset: extra = passwords_keyset - users_set missing = users_set - passwords_keyset raise ValidationError( _("Request did not contain required passwords. " + "Extra passwords: " + str(list(extra)) + " " "Missing passwords: " + str(list(missing)))) # TODO: Check password signatures # Load uploaders public key user = self.context['request'].user public_key = user.public_key.first().as_key() for dicty in passwords: user_pk = int(dicty['user_pk']) encoded_password = dicty['password'] encoded_signature = dicty['signature'] if user_pk not in users_set: raise ValidationError(_("Some users could not be looked up.")) password = Password(key_entry=keyentry, public_key=key, password=encoded_password, signature=encoded_signature, signing_key=public_key) password.full_clean() return data def create(self, validated_data): passwords = validated_data['passwords_write'] del validated_data['passwords_write'] del validated_data['user'] with transaction.atomic(savepoint=True): keyentry = KeyEntry.objects.create(**validated_data) for dicty in passwords: user_pk = dicty['user_pk'] password = dicty['password'] Password.objects.create( key_entry=keyentry, user=get_user_model().objects.get(pk=user_pk), password=password) return keyentry
class BadgeInstanceSerializerV2(DetailSerializerV2, OriginalJsonSerializerMixin): openBadgeId = serializers.URLField(source='jsonld_id', read_only=True) createdAt = DateTimeWithUtcZAtEndField(source='created_at', read_only=True, default_timezone=pytz.utc) createdBy = EntityRelatedFieldV2(source='cached_creator', read_only=True) badgeclass = EntityRelatedFieldV2(source='cached_badgeclass', required=False, queryset=BadgeClass.cached) badgeclassOpenBadgeId = CachedUrlHyperlinkedRelatedField( source='badgeclass_jsonld_id', view_name='badgeclass_json', lookup_field='entity_id', queryset=BadgeClass.cached, required=False) badgeclassName = serializers.CharField(write_only=True, required=False) issuer = EntityRelatedFieldV2(source='cached_issuer', required=False, queryset=Issuer.cached) issuerOpenBadgeId = serializers.URLField(source='issuer_jsonld_id', read_only=True) image = ValidImageField(read_only=True, use_public=True, source='*') recipient = BadgeRecipientSerializerV2(source='*', required=False) issuedOn = DateTimeWithUtcZAtEndField(source='issued_on', required=False, default_timezone=pytz.utc) narrative = MarkdownCharField(required=False, allow_null=True) evidence = EvidenceItemSerializerV2(source='evidence_items', many=True, required=False) revoked = HumanReadableBooleanField(read_only=True) revocationReason = serializers.CharField(source='revocation_reason', read_only=True) acceptance = serializers.CharField(read_only=True) expires = DateTimeWithUtcZAtEndField(source='expires_at', required=False, allow_null=True, default_timezone=pytz.utc) notify = HumanReadableBooleanField(write_only=True, required=False, default=False) allowDuplicateAwards = serializers.BooleanField(write_only=True, required=False, default=True) extensions = serializers.DictField(source='extension_items', required=False, validators=[BadgeExtensionValidator()]) class Meta(DetailSerializerV2.Meta): model = BadgeInstance apispec_definition = ('Assertion', { 'properties': OrderedDict([ ('entityId', { 'type': "string", 'format': "string", 'description': "Unique identifier for this Assertion", 'readOnly': True, }), ('entityType', { 'type': "string", 'format': "string", 'description': "\"Assertion\"", 'readOnly': True, }), ('openBadgeId', { 'type': "string", 'format': "url", 'description': "URL of the OpenBadge compliant json", 'readOnly': True, }), ('createdAt', { 'type': 'string', 'format': 'ISO8601 timestamp', 'description': "Timestamp when the Assertion was created", 'readOnly': True, }), ('createdBy', { 'type': 'string', 'format': 'entityId', 'description': "BadgeUser who created the Assertion", 'readOnly': True, }), ('badgeclass', { 'type': 'string', 'format': 'entityId', 'description': "BadgeClass that issued this Assertion", 'required': False, }), ('badgeclassOpenBadgeId', { 'type': 'string', 'format': 'url', 'description': "URL of the BadgeClass to award", 'required': False, }), ('badgeclassName', { 'type': 'string', 'format': 'string', 'description': "Name of BadgeClass to create assertion against, case insensitive", 'required': False, }), ('revoked', { 'type': 'boolean', 'description': "True if this Assertion has been revoked", 'readOnly': True, }), ('revocationReason', { 'type': 'string', 'format': "string", 'description': "Short description of why the Assertion was revoked", 'readOnly': True, }), ('acceptance', { 'type': 'string', 'description': "Recipient interaction with Assertion. One of: Unaccepted, Accepted, or Rejected", 'readOnly': True, }), ('image', { 'type': 'string', 'format': 'url', 'description': "URL to the baked assertion image", 'readOnly': True, }), ('issuedOn', { 'type': 'string', 'format': 'ISO8601 timestamp', 'description': "Timestamp when the Assertion was issued", 'required': False, }), ('narrative', { 'type': 'string', 'format': 'markdown', 'description': "Markdown narrative of the achievement", 'required': False, }), ('evidence', { 'type': 'array', 'items': { '$ref': '#/definitions/AssertionEvidence' }, 'description': "List of evidence associated with the achievement", 'required': False, }), ('recipient', { 'type': 'object', '$ref': '#/definitions/BadgeRecipient', 'description': "Recipient that was issued the Assertion", 'required': False, }), ('expires', { 'type': 'string', 'format': 'ISO8601 timestamp', 'description': "Timestamp when the Assertion expires", 'required': False, }), ]) }) def validate_issuedOn(self, value): if value > timezone.now(): raise serializers.ValidationError("Only issuedOn dates in the past are acceptable.") if value.year < 1583: raise serializers.ValidationError("Only issuedOn dates after the introduction of the Gregorian calendar are allowed.") return value def update(self, instance, validated_data): updateable_fields = [ 'evidence_items', 'expires_at', 'extension_items', 'hashed', 'issued_on', 'narrative', 'recipient_identifier', 'recipient_type' ] for field_name in updateable_fields: if field_name in validated_data: setattr(instance, field_name, validated_data.get(field_name)) instance.rebake(save=True) return instance def create(self, validated_data): if 'cached_issuer' in validated_data: # ignore issuer in request validated_data.pop('cached_issuer') return super().create(validated_data) def validate(self, data): request = self.context.get('request', None) expected_issuer = self.context.get('kwargs', {}).get('issuer') badgeclass_identifiers = ['badgeclass_jsonld_id', 'badgeclassName', 'cached_badgeclass', 'badgeclass'] badge_instance_properties = list(data.keys()) if 'badgeclass' in self.context: badge_instance_properties.append('badgeclass') if sum([el in badgeclass_identifiers for el in badge_instance_properties]) > 1: raise serializers.ValidationError('Multiple badge class identifiers. Exactly one of the following badge class identifiers are allowed: badgeclass, badgeclassName, or badgeclassOpenBadgeId') if request and request.method != 'PUT': # recipient and badgeclass are only required on create, ignored on update if 'recipient_identifier' not in data: raise serializers.ValidationError({'recipient': ["This field is required"]}) if 'cached_badgeclass' in data: # included badgeclass in request data['badgeclass'] = data.pop('cached_badgeclass') elif 'badgeclass' in self.context: # badgeclass was passed in context data['badgeclass'] = self.context.get('badgeclass') elif 'badgeclass_jsonld_id' in data: data['badgeclass'] = data.pop('badgeclass_jsonld_id') elif 'badgeclassName' in data: name = data.pop('badgeclassName') matches = BadgeClass.objects.filter(name=name, issuer=expected_issuer) len_matches = len(matches) if len_matches == 1: data['badgeclass'] = matches.first() elif len_matches == 0: raise serializers.ValidationError("No matching BadgeClass found with name {}".format(name)) else: raise serializers.ValidationError("Could not award; {} BadgeClasses with name {}".format(len_matches, name)) else: raise serializers.ValidationError({"badgeclass": ["This field is required"]}) allow_duplicate_awards = data.pop('allowDuplicateAwards') if allow_duplicate_awards is False: previous_awards = BadgeInstance.objects.filter( recipient_identifier=data['recipient_identifier'], badgeclass=data['badgeclass'] ).filter( revoked=False ).filter( Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now()) ) if previous_awards.exists(): raise serializers.ValidationError( "A previous award of this badge already exists for this recipient.") if expected_issuer and data['badgeclass'].issuer_id != expected_issuer.id: raise serializers.ValidationError({"badgeclass": ["Could not find matching badgeclass for this issuer."]}) if 'badgeclass' in data: data['issuer'] = data['badgeclass'].issuer return data
class PredictionsTableSerializer(serializers.ListSerializer): child = serializers.DictField(child=serializers.CharField())
class CreateEventSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True) event_logistics = serializers.ListField( child=serializers.DictField( child=serializers.CharField(required=False) ), required=False, write_only=True ) hosts = serializers.ListField( child=serializers.IntegerField(), required=False, write_only=True ) def validate_hosts(self, hosts): for host in hosts: if not OrgHost.objects.filter(pk=host).exists() and not SangguHost.objects.filter(pk=host).exists() and not OfficeHost.objects.filter(pk=host).exists(): raise serializers.ValidationError("Host with index {} does not exist".format(host)) return hosts def validate_event_logistics(self, logistics): for logistic in logistics: try: datetime.strptime(logistic['date'], "%Y-%m-%d") except ValueError: raise serializers.ValidationError("Date is not valid") try: time.strptime(logistic['start_time'], "%H:%M:%S") except ValueError: raise serializers.ValidationError("Start time is not valid") try: time.strptime(logistic['end_time'], "%H:%M:%S") except ValueError: raise serializers.ValidationError("End time is not valid") if 'venue' in logistic and not Venue.objects.filter(pk=int(logistic['venue'])).exists(): raise serializers.ValidationError("Venue does not exist") return logistics def create(self, validated_data): return save_event(validated_data, None) def update(self, instance, validated_data): return save_event(validated_data, instance) class Meta: model = Event fields = ['id', 'name', 'hosts', 'sanggu_hosts', 'office_hosts', 'org_hosts', 'description', 'poster_url', 'event_url', 'tags', 'audience', 'event_logistics']
class InstanceSerializer(serializers.ModelSerializer): """ This is a 'utility serializer' it should be used for preparing a v2 POST *ONLY* This serializer should *never* be returned to the user. instead, the core instance should be re-serialized into a 'details serializer' """ identity = serializers.SlugRelatedField(source='created_by_identity', slug_field='uuid', queryset=Identity.objects.all()) provider_uuid = serializers.SlugRelatedField( source='created_by_identity.provider', slug_field='uuid', read_only=True) uuid = serializers.CharField(source='provider_alias', read_only=True) name = serializers.CharField() project = serializers.SlugRelatedField(source="projects", slug_field="uuid", queryset=Project.objects.all(), required=False, allow_null=True) scripts = serializers.SlugRelatedField(slug_field="uuid", queryset=BootScript.objects.all(), many=True, required=False) #NOTE: These 'alias' point to the 'cloud/native IDs' NOT the db-UUID! #NOTE: source_alias should belong to volume.identifier or providermachine.identifier source_alias = serializers.SlugRelatedField( source="source", slug_field="identifier", queryset=InstanceSource.objects.all()) size_alias = serializers.SlugRelatedField( source="instancestatushistory_set.size", slug_field="alias", queryset=Size.objects.all()) # Optional kwargs to be inluded deploy = serializers.BooleanField(default=True) extra = serializers.DictField(required=False) def to_internal_value(self, data): """ Overwrite to force custom logic required before accepting data to launch an instance. 1. check of identity prior to checking size_alias or source_alias NOTE: This is required because we have identical alias' on multiple providers, so we must first filter-down based on the identity requested for launching the instance. 2. Check source_alias is either a Volume or a ProviderMachine before continuing. """ identity_uuid = data.get('identity') if not identity_uuid: raise ValidationError({'identity': 'This field is required.'}) size_queryset = self.fields['size_alias'].queryset source_queryset = self.fields['source_alias'].queryset size_alias = data.get('size_alias') if not size_alias: raise ValidationError({'size_alias': 'This field is required.'}) size = size_queryset.filter(alias=size_alias) if not size: raise ValidationError( {'size_alias': 'Value %s did not match a Size.' % size_alias}) source_alias = data.get('source_alias') if not source_alias: raise ValidationError({'source_alias': 'This field is required.'}) source = InstanceSource.get_source(source_alias, queryset=source_queryset) if not source: raise ValidationError({ 'source_alias': 'Value %s did not match a ProviderMachine or Volume.' % source_alias }) return super(InstanceSerializer, self).to_internal_value(data) def __init__(self, *args, **kwargs): """ As of DRF 3.2.4 This is the *ONLY* way to 'limit_choices_to' or to dynamically assign a queryset based on the data passed to the serializer. See https://github.com/tomchristie/django-rest-framework/issues/1811 AND https://github.com/tomchristie/django-rest-framework/issues/1985 For a 'Future-Proof' solution. """ # This is required to be passed in identity_uuid = kwargs.get('data', {}).get('identity') if not identity_uuid: super(InstanceSerializer, self).__init__(*args, **kwargs) return #request_user = self.context['request'].user # These fields have querysets that are *dynamic* based on provider (uuid) project_f = self.fields['project'] provider_f = self.fields['provider_uuid'] size_f = self.fields['size_alias'] source_f = self.fields['source_alias'] provider_queryset = Provider.objects.filter( identity__uuid=identity_uuid) if not provider_queryset: project_f.queryset = project_f.queryset.none() size_f.queryset = size_f.queryset.none() source_f.queryset = source_f.queryset.none() elif len(provider_queryset) > 1: raise Exception( "Implementation Error -- Only ever expected one value here! Fix this line!" ) else: #ASSERT: Queryset is EXACTLY ONE value. provider_f.queryset = provider_queryset provider_uuid = provider_queryset.first().uuid source_f.queryset = source_f.queryset.filter( provider__uuid=provider_uuid) size_f.queryset = size_f.queryset.filter( provider__uuid=provider_uuid) super(InstanceSerializer, self).__init__(*args, **kwargs) class Meta: model = Instance fields = ( 'uuid', 'provider_uuid', 'identity', 'name', 'project', 'size_alias', 'source_alias', 'scripts', 'deploy', 'extra', )
class CourseGoalsSerializer(serializers.Serializer): """ Serializer for Course Goal data """ selected_goal = serializers.DictField() weekly_learning_goal_enabled = serializers.BooleanField(default=False)
class NestedTrackingSummarySerializer(serializers.Serializer): opened = serializers.DateTimeField(source='first_open') open_time = serializers.IntegerField() clicked = serializers.ListField(source='clicks', child=serializers.DictField())
class PickupRequest(serializers.Serializer): date = serializers.CharField(required=False, help_text='Pickup date') account_number = serializers.CharField(required=False, help_text='Shipper account number') weight = serializers.FloatField(required=False, help_text='Shipment total weight') weight_unit = serializers.ChoiceField(required=False, default="KG", choices=WeightChoices, help_text=""" General package weight unit. Supported Units: "LB" (Pound), "KG" (Kilogram) default: 'KG' """) pieces = serializers.FloatField(required=False, help_text='Number of shipment pieces') ready_time = serializers.CharField(required=False, help_text=""" Shipment ready time for pickup. Format: '00:00', 'TT:MM' """) closing_time = serializers.CharField(required=False, help_text=""" Pickup location closing time. Format: '00:00', 'TT:MM' """) instruction = serializers.CharField(required=False, help_text='Pickup instruction') package_location = serializers.CharField(required=False, help_text=""" Shipment items location. Ex: Back of the entrance door """) city = serializers.CharField(required=False, help_text='Pickup address city') postal_code = serializers.CharField(required=False, help_text='Pickup address postal code') state = serializers.CharField( required=False, help_text='Pickup address state or province name') state_code = serializers.CharField( required=False, help_text='Pickup address state or province code') country_name = serializers.CharField( required=False, help_text='Pickup address country name') country_code = serializers.CharField( required=False, help_text='Pickup address country code') person_name = serializers.CharField(required=False, help_text='Pickup attention name') company_name = serializers.CharField( required=False, help_text='Pickup company name (if company)') phone_number = serializers.CharField(required=False, help_text='Phone number') email_address = serializers.CharField(required=False, help_text='Email address') is_business = serializers.BooleanField( required=False, help_text='Flag to specify if pickup address is a business') confirmation_number = serializers.CharField( required=False, help_text= 'Pickup confirmation number (only required for a pickup update)') address_lines = StringListField(required=False, help_text='Address lines') extra = serializers.DictField( required=False, help_text= "extra field for special details supported by a specific carriers")
class Shipment(serializers.Serializer): items = serializers.ListField(child=Item(), help_text='list of shipment items') insured_amount = serializers.FloatField(required=False, help_text='Insured amount') total_items = serializers.IntegerField(required=False, help_text='Number of items') packaging_type = serializers.ChoiceField(required=False, default="BOX", choices=PackagingChoices, help_text=""" shipment packaging type default: 'BOX' """) is_document = serializers.BooleanField( required=False, help_text= 'Document only shipment flag. (Non dutiable for international shipping)' ) currency = serializers.ChoiceField( required=False, choices=Currencies, help_text="""General shipment values currency""") total_weight = serializers.FloatField(required=False, help_text='Total shipment weight') weight_unit = serializers.ChoiceField(required=False, default='KG', choices=WeightChoices, help_text=""" General package weight unit. Supported Units: "LB" (Pound), "KG" (Kilogram) default: 'KG' """) dimension_unit = serializers.ChoiceField(required=False, default='CM', choices=DimensionChoices, help_text=""" General package dimensions unit. Supported Units: "IN" (Inch), "CM" (Centimeter) default: 'CM' """) paid_by = serializers.ChoiceField(required=False, choices=PayorChoices, help_text=""" Shipment paid by. Values: "SENDER", "THIRD_PARTY", "RECIPIENT" """) payment_country_code = serializers.CharField( required=False, help_text='Payment country code') payment_account_number = serializers.CharField( required=False, help_text='Shipment payment account number') services = StringListField( required=False, help_text='Shipment services (check carriers services docs)') options = serializers.ListField( child=Option(), required=False, help_text='Shipping sepcial services and option') date = serializers.CharField(required=False, help_text='Shipment date') payment_type = serializers.CharField(required=False, help_text=""" Payment type: account_number, credit_card """) duty_paid_by = serializers.ChoiceField(required=False, default='SENDER', choices=PayorChoices, help_text=""" Shipment paid by. Values: "SENDER", "THIRD_PARTY", "RECIPIENT" default: 'SENDER' """) duty_payment_account = serializers.CharField( required=False, help_text='Duty payer account number') declared_value = serializers.FloatField(required=False, help_text='Shipment total value') customs = Customs(required=False, help_text='Customs paperwork details') references = StringListField(required=False, help_text=""" Shipment references. Ex: order number, platform reference... """) label = Doc(required=False, help_text='Label specification details') invoice = Invoice(required=False, help_text='Shipment invoice details') doc_images = serializers.ListField( child=Doc(), required=False, help_text='All required documents files. eg: invoice...') ship_date = serializers.CharField( required=False, help_text='Expected shipment date (supported by certain carriers)') extra = serializers.DictField( required=False, help_text= "extra field for special details supported by a specific carriers")
class RoutineSerializer(serializers.ModelSerializer): exercises = RoutineUnitSerializer(source="routine_units", many=True, required=False) owner_username = serializers.CharField(source="owner.username", read_only=True) kind_display = serializers.CharField(source="get_kind_display", read_only=True) can_be_forked = serializers.SerializerMethodField("_can_be_forked", read_only=True) can_be_modified = serializers.SerializerMethodField("_can_be_modified", read_only=True) muscles_count = serializers.DictField(read_only=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Passing context to the nested serializer (context contain user pk, which is required for # validating exercise owner match routine owner) self.fields["exercises"].context.update(self.context) def _can_be_forked(self, obj): requesting_user_pk = self.context.get("requesting_user_pk") if requesting_user_pk is not None: return obj.can_be_forked(requesting_user_pk) return None def _can_be_modified(self, obj): requesting_user_pk = self.context.get("requesting_user_pk") if requesting_user_pk is not None: return obj.can_be_modified(requesting_user_pk) return None class Meta: model = Routine fields = ( "pk", "name", "kind", "kind_display", "owner", "owner_username", "instructions", "can_be_forked", "can_be_modified", "forks_count", "exercises", "muscles_count", ) validators = [ UniqueTogetherValidator( queryset=Routine.objects.all(), fields=["name", "owner"], message="You already own this routine.", ) ] def create(self, validated_data): routine_units = validated_data.pop("routine_units", []) instance = Routine(**validated_data) instance.save() # Setup many to many relations for routine_unit in routine_units: exercise = routine_unit.pop("exercise") instance.exercises.add(exercise, through_defaults=routine_unit) return instance def update(self, instance, validated_data): instance.name = validated_data.get("name") instance.kind = validated_data.get("kind") instance.instructions = validated_data.get("instructions") # Clear and setup again many to many relations instance.exercises.clear() for routine_unit in validated_data["routine_units"]: exercise = routine_unit.pop("exercise") instance.exercises.add(exercise, through_defaults=routine_unit) instance.save() return instance
class CollectionVersionSerializer(SingleArtifactContentSerializer, ContentChecksumSerializer): """ A serializer for CollectionVersion Content. """ id = serializers.UUIDField(source="pk", help_text="A collection identifier.") authors = serializers.ListField( help_text=_("A list of the CollectionVersion content's authors."), child=serializers.CharField(max_length=64), ) contents = serializers.ListField( child=serializers.DictField(), help_text=_("A JSON field with data about the contents.")) dependencies = serializers.DictField(help_text=_( "A dict declaring Collections that this collection requires to be installed for it to " "be usable.")) description = serializers.CharField( help_text=_("A short summary description of the collection."), allow_blank=True) docs_blob = serializers.DictField(help_text=_( "A JSON field holding the various documentation blobs in the collection." )) manifest = serializers.DictField( help_text=_("A JSON field holding MANIFEST.json data.")) files = serializers.DictField( help_text=_("A JSON field holding FILES.json data.")) documentation = serializers.CharField( help_text=_("The URL to any online docs."), allow_blank=True, max_length=2000) homepage = serializers.CharField( help_text=_("The URL to the homepage of the collection/project."), allow_blank=True, max_length=2000, ) issues = serializers.CharField( help_text=_("The URL to the collection issue tracker."), allow_blank=True, max_length=2000) license = serializers.ListField( help_text=_("A list of licenses for content inside of a collection."), child=serializers.CharField(max_length=32), ) name = serializers.CharField(help_text=_("The name of the collection."), max_length=64) namespace = serializers.CharField( help_text=_("The namespace of the collection."), max_length=64) repository = serializers.CharField( help_text=_("The URL of the originating SCM repository."), allow_blank=True, max_length=2000) tags = TagNestedSerializer(many=True, read_only=True) version = serializers.CharField( help_text=_("The version of the collection."), max_length=128) requires_ansible = serializers.CharField( help_text=_("The version of Ansible required to use the collection. " "Multiple versions can be separated with a comma."), allow_null=True, required=False, max_length=255, ) class Meta: fields = (tuple( set(SingleArtifactContentSerializer.Meta.fields) - {"relative_path"}) + ContentChecksumSerializer.Meta.fields + ( "id", "authors", "contents", "dependencies", "description", "docs_blob", "manifest", "files", "documentation", "homepage", "issues", "license", "name", "namespace", "repository", "tags", "version", "requires_ansible", )) model = CollectionVersion
class CreateVnfPkgInfoRequestSerializer(serializers.Serializer): userDefinedData = serializers.DictField(help_text="User defined data for the VNF package.", required=False, allow_null=True)
class CellBasicSerializer(serializers.ModelSerializer): """This class represents the Cell model serializer.""" address = serializers.DictField() managers = serializers.ListField(required=False) def create(self, validated_data): cell = models.Cell() cell.name = validated_data['name'] if 'managers' in validated_data.keys(): managers = validated_data['managers'] else: managers = None address_data = validated_data['address'] country_data = validated_data['address']['country'] state_province_data = validated_data['address']['state_province'] address_data['country'] = country_data['iso_code'] address_data['state_province'] = state_province_data['iso_code'] try: cell_address = Address.objects.get(**address_data) except Address.DoesNotExist: try: cell_address = Address() cell_address.__dict__.update(validated_data['address']) cell_address.country, created = Country.objects.get_or_create( name__iexact=country_data['name'], iso_code__iexact=country_data['iso_code'], defaults={ 'iso_code': country_data['iso_code'], 'name': country_data['name'], }, ) except IntegrityError as err: if 'UNIQUE constraint failed' in err.args[0]: error = { 'message': ("A Country with that iso_code already exists" if err.args else "Unknown Error") } raise serializers.ValidationError(error) try: cell_address.state_province, created = ( StateProvince.objects.get_or_create( iso_code__iexact=state_province_data['iso_code'], name__iexact=state_province_data['name'], country=cell_address.country, defaults={ 'iso_code': state_province_data['iso_code'], 'name': state_province_data['name'], }, )) cell_address.save() except IntegrityError as err: if 'UNIQUE constraint failed' in err.args[0]: error = { 'message': ("A StateProvince with that iso_code already exists" if err.args else "Unknown Error") } raise serializers.ValidationError(error) cell.address = cell_address list_manager = list() if managers: for manager in managers: try: user = User.objects.get(id=manager) list_manager.append(user) except Exception as err: error = { 'message': ("Unknown user with this ID" if err.args else "Unknown Error") } raise serializers.ValidationError(error) cell.save() for user in list_manager: cell.managers.add(user) return cell def update(self, instance, validated_data): if 'name' in validated_data.keys(): instance.name = validated_data['name'] if 'managers' in validated_data.keys(): # Remove all managers of the cell instance.managers.clear() for manager in validated_data['managers']: try: user = User.objects.get(id=manager) instance.managers.add(user) except Exception as err: error = { 'message': ("Unknown user with this ID" if err.args else "Unknown Error") } raise serializers.ValidationError(error) if 'address' in validated_data.keys(): try: address_data = validated_data['address'] country_data = validated_data['address']['country'] state_province_data = \ validated_data['address']['state_province'] address_data['country'] = country_data['iso_code'] address_data['state_province'] = \ state_province_data['iso_code'] except KeyError as err: error = { 'message': ("Please specify a complete valid address." if err.args else "Unknown Error") } raise serializers.ValidationError(error) try: cell_address = Address.objects.get(**address_data) except Address.DoesNotExist: try: cell_address = Address() cell_address.__dict__.update(validated_data['address']) cell_address.country, created = \ Country.objects.get_or_create( name__iexact=country_data['name'], iso_code__iexact=country_data['iso_code'], defaults={ 'iso_code': country_data['iso_code'], 'name': country_data['name'], }, ) except IntegrityError as err: if 'UNIQUE constraint failed' in err.args[0]: error = { 'message': ("A Country with that iso_code already exists" if err.args else "Unknown Error") } raise serializers.ValidationError(error) try: cell_address.state_province, created = ( StateProvince.objects.get_or_create( iso_code__iexact=state_province_data['iso_code'], name__iexact=state_province_data['name'], country=cell_address.country, defaults={ 'iso_code': state_province_data['iso_code'], 'name': state_province_data['name'], }, )) cell_address.save() except IntegrityError as err: if 'UNIQUE constraint failed' in err.args[0]: error = { 'message': ("A StateProvince with " "that iso_code already exists" if err.args else "Unknown Error") } raise serializers.ValidationError(error) instance.address = cell_address instance.save() return instance def to_representation(self, instance): data = dict() data['id'] = instance.id data['name'] = instance.name data['address'] = AddressBasicSerializer( instance.address).to_representation(instance.address) data['managers'] = list() for manager in instance.managers.all(): data['managers'].append( UserPublicSerializer(manager).to_representation(manager)) return data class Meta: model = models.Cell depth = 1 fields = ('id', 'name', 'address', 'managers') read_only_fields = [ 'id', ]
class BadgeClassSerializerV2(DetailSerializerV2, OriginalJsonSerializerMixin): openBadgeId = serializers.URLField(source='jsonld_id', read_only=True) createdAt = DateTimeWithUtcZAtEndField(source='created_at', read_only=True) createdBy = EntityRelatedFieldV2(source='cached_creator', read_only=True) issuer = EntityRelatedFieldV2(source='cached_issuer', required=False, queryset=Issuer.cached) issuerOpenBadgeId = serializers.URLField(source='issuer_jsonld_id', read_only=True) name = StripTagsCharField(max_length=1024) image = ValidImageField(required=False, use_public=True, source='*') description = StripTagsCharField(max_length=16384, required=True, convert_null=True) criteriaUrl = StripTagsCharField(source='criteria_url', required=False, allow_null=True, validators=[URLValidator()]) criteriaNarrative = MarkdownCharField(source='criteria_text', required=False, allow_null=True) alignments = AlignmentItemSerializerV2(source='alignment_items', many=True, required=False) tags = serializers.ListField(child=StripTagsCharField(max_length=1024), source='tag_items', required=False) expires = BadgeClassExpirationSerializerV2(source='*', required=False, allow_null=True) extensions = serializers.DictField(source='extension_items', required=False, validators=[BadgeExtensionValidator()]) class Meta(DetailSerializerV2.Meta): model = BadgeClass apispec_definition = ('BadgeClass', { 'properties': OrderedDict([ ('entityId', { 'type': "string", 'format': "string", 'description': "Unique identifier for this BadgeClass", 'readOnly': True, }), ('entityType', { 'type': "string", 'format': "string", 'description': "\"BadgeClass\"", 'readOnly': True, }), ('openBadgeId', { 'type': "string", 'format': "url", 'description': "URL of the OpenBadge compliant json", 'readOnly': True, }), ('createdAt', { 'type': 'string', 'format': 'ISO8601 timestamp', 'description': "Timestamp when the BadgeClass was created", 'readOnly': True, }), ('createdBy', { 'type': 'string', 'format': 'entityId', 'description': "BadgeUser who created this BadgeClass", 'readOnly': True, }), ('issuer', { 'type': 'string', 'format': 'entityId', 'description': "entityId of the Issuer who owns the BadgeClass", 'required': False, }), ('name', { 'type': "string", 'format': "string", 'description': "Name of the BadgeClass", 'required': True, }), ('description', { 'type': "string", 'format': "string", 'description': "Short description of the BadgeClass", 'required': True, }), ('image', { 'type': "string", 'format': "data:image/png;base64", 'description': "Base64 encoded string of an image that represents the BadgeClass.", 'required': False, }), ('criteriaUrl', { 'type': "string", 'format': "url", 'description': "External URL that describes in a human-readable format the criteria for the BadgeClass", 'required': False, }), ('criteriaNarrative', { 'type': "string", 'format': "markdown", 'description': "Markdown formatted description of the criteria", 'required': False, }), ('tags', { 'type': "array", 'items': { 'type': "string", 'format': "string" }, 'description': "List of tags that describe the BadgeClass", 'required': False, }), ('alignments', { 'type': "array", 'items': { '$ref': '#/definitions/BadgeClassAlignment' }, 'description': "List of objects describing objectives or educational standards", 'required': False, }), ('expires', { '$ref': "#/definitions/BadgeClassExpiration", 'description': "Expiration period for Assertions awarded from this BadgeClass", 'required': False, }), ]) }) def to_internal_value(self, data): if not isinstance(data, BadgeClass) and 'expires' in data: if not data['expires'] or len(data['expires']) == 0: # if expires was included blank, remove it so to_internal_value() doesnt choke del data['expires'] return super(BadgeClassSerializerV2, self).to_internal_value(data) def update(self, instance, validated_data): if 'cached_issuer' in validated_data: validated_data.pop('cached_issuer') # issuer is not updatable if 'image' in validated_data: self.context['save_kwargs'] = dict(force_resize=True) if not IsEditor().has_object_permission(self.context.get('request'), None, instance.issuer): raise serializers.ValidationError( {"issuer": "You do not have permission to edit badges on this issuer."}) return super(BadgeClassSerializerV2, self).update(instance, validated_data) def create(self, validated_data): if 'image' not in validated_data: raise serializers.ValidationError({'image': 'Valid image file or data URI required.'}) if 'cached_issuer' in validated_data: # included issuer in request validated_data['issuer'] = validated_data.pop('cached_issuer') elif 'issuer' in self.context: # issuer was passed in context validated_data['issuer'] = self.context.get('issuer') else: # issuer is required on create raise serializers.ValidationError({"issuer": "This field is required"}) if not IsEditor().has_object_permission(self.context.get('request'), None, validated_data['issuer']): raise serializers.ValidationError({"issuer": "You do not have permission to edit badges on this issuer."}) return super(BadgeClassSerializerV2, self).create(validated_data)
class PreprintSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'id', 'title', 'tags', 'date_created', 'date_modified', 'contributors', 'subjects', 'doi' ]) title = ser.CharField(required=False) subjects = JSONAPIListField(child=TaxonomyField(), required=False, source='preprint_subjects') provider = ser.CharField(source='preprint_provider', required=False) date_created = ser.DateTimeField(read_only=True, source='preprint_created') date_modified = ser.DateTimeField(read_only=True) id = IDField(source='_id', required=False) abstract = ser.CharField(source='description', required=False) tags = JSONAPIListField(child=NodeTagField(), required=False) doi = ser.CharField(source='preprint_doi', required=False) csl = ser.DictField(read_only=True) primary_file = PrimaryFileRelationshipField( related_view='files:file-detail', related_view_kwargs={'file_id': '<preprint_file._id>'}, lookup_url_kwarg='file_id', read_only=False ) files = RelationshipField( related_view='nodes:node-providers', related_view_kwargs={'node_id': '<pk>'} ) providers = RelationshipField( related_view='preprints:preprint-preprint_providers', related_view_kwargs={'node_id': '<pk>'}, self_view='preprints:preprint-relationships-preprint_providers', self_view_kwargs={'node_id': '<pk>'} ) links = LinksField( { 'self': 'get_preprint_url', 'html': 'get_absolute_html_url', 'doi': 'get_doi_url' } ) contributors = RelationshipField( related_view='nodes:node-contributors', related_view_kwargs={'node_id': '<pk>'}, related_meta={'count': 'get_contrib_count'}, ) class Meta: type_ = 'preprints' def get_preprint_url(self, obj): return absolute_reverse('preprints:preprint-detail', kwargs={'node_id': obj._id}) def get_absolute_url(self, obj): return self.get_preprint_url(obj) def get_doi_url(self, obj): return 'https://dx.doi.org/{}'.format(obj.preprint_doi) if obj.preprint_doi else None def create(self, validated_data): node = Node.load(validated_data.pop('_id', None)) if not node: raise exceptions.NotFound('Unable to find Node with specified id.') auth = get_user_auth(self.context['request']) if not node.has_permission(auth.user, permissions.ADMIN): raise exceptions.PermissionDenied if node.is_preprint: raise Conflict('This node already stored as a preprint, use the update method instead.') primary_file = validated_data.pop('primary_file', None) if not primary_file: raise exceptions.ValidationError(detail='You must specify a primary_file to create a preprint.') self.set_node_field(node.set_preprint_file, primary_file, auth) subjects = validated_data.pop('preprint_subjects', None) if not subjects: raise exceptions.ValidationError(detail='You must specify at least one subject to create a preprint.') self.set_node_field(node.set_preprint_subjects, subjects, auth) tags = validated_data.pop('tags', None) if tags: for tag in tags: node.add_tag(tag, auth, save=False, log=False) for key, value in validated_data.iteritems(): setattr(node, key, value) try: node.save() except ValidationValueError as e: raise exceptions.ValidationError(detail=e.message) # Send preprint confirmation email signal to new authors on preprint! for author in node.contributors: if author != auth.user: project_signals.contributor_added.send(node, contributor=author, auth=auth, email_template='preprint') return node def update(self, node, validated_data): from website.models import Node assert isinstance(node, Node), 'You must specify a valid node to be updated.' auth = get_user_auth(self.context['request']) primary_file = validated_data.pop('primary_file', None) if primary_file: self.set_node_field(node.set_preprint_file, primary_file, auth) subjects = validated_data.pop('preprint_subjects', None) if subjects: self.set_node_field(node.set_preprint_subjects, subjects, auth) old_tags = set([tag._id for tag in node.tags]) if 'tags' in validated_data: current_tags = set(validated_data.pop('tags', [])) elif self.partial: current_tags = set(old_tags) else: current_tags = set() for new_tag in (current_tags - old_tags): node.add_tag(new_tag, auth=auth) for deleted_tag in (old_tags - current_tags): node.remove_tag(deleted_tag, auth=auth) for key, value in validated_data.iteritems(): setattr(node, key, value) try: node.save() except ValidationValueError as e: raise exceptions.ValidationError(detail=e.message) return node def set_node_field(self, func, val, auth): try: func(val, auth, save=False) except PermissionsError: raise exceptions.PermissionDenied('Not authorized to update this node.') except ValueError as e: raise exceptions.ValidationError(detail=e.message)
class IssuerSerializerV2(DetailSerializerV2, OriginalJsonSerializerMixin): openBadgeId = serializers.URLField(source='jsonld_id', read_only=True) createdAt = DateTimeWithUtcZAtEndField(source='created_at', read_only=True) createdBy = EntityRelatedFieldV2(source='cached_creator', queryset=BadgeUser.cached, required=False) name = StripTagsCharField(max_length=1024) image = ValidImageField(required=False, use_public=True, source='*') email = serializers.EmailField(max_length=255, required=True) description = StripTagsCharField(max_length=16384, required=False) url = serializers.URLField(max_length=1024, required=True) staff = IssuerStaffSerializerV2(many=True, source='staff_items', required=False) extensions = serializers.DictField(source='extension_items', required=False, validators=[BadgeExtensionValidator()]) badgrDomain = serializers.SlugRelatedField( required=False, source='badgrapp', slug_field='cors', queryset=BadgrApp.objects ) class Meta(DetailSerializerV2.Meta): model = Issuer apispec_definition = ('Issuer', { 'properties': OrderedDict([ ('entityId', { 'type': "string", 'format': "string", 'description': "Unique identifier for this Issuer", 'readOnly': True, }), ('entityType', { 'type': "string", 'format': "string", 'description': "\"Issuer\"", 'readOnly': True, }), ('openBadgeId', { 'type': "string", 'format': "url", 'description': "URL of the OpenBadge compliant json", 'readOnly': True, }), ('createdAt', { 'type': 'string', 'format': 'ISO8601 timestamp', 'description': "Timestamp when the Issuer was created", 'readOnly': True, }), ('createdBy', { 'type': 'string', 'format': 'entityId', 'description': "BadgeUser who created this Issuer", 'required': False, }), ('name', { 'type': "string", 'format': "string", 'description': "Name of the Issuer", 'required': True, }), ('image', { 'type': "string", 'format': "data:image/png;base64", 'description': "Base64 encoded string of an image that represents the Issuer", 'required': False, }), ('email', { 'type': "string", 'format': "email", 'description': "Contact email for the Issuer", 'required': True, }), ('url', { 'type': "string", 'format': "url", 'description': "Homepage or website associated with the Issuer", 'required': False, }), ('description', { 'type': "string", 'format': "text", 'description': "Short description of the Issuer", 'required': False, }), ]) }) def validate_image(self, image): if image is not None: img_name, img_ext = os.path.splitext(image.name) image.name = 'issuer_logo_' + str(uuid.uuid4()) + img_ext return image def validate_createdBy(self, val): if not request_authenticated_with_server_admin_token(self.context.get('request')): return None return val def validate(self, data): if data.get('badgrapp') and not request_authenticated_with_server_admin_token(self.context.get('request')): data.pop('badgrapp') return data def create(self, validated_data): request = self.context.get('request') # If a Server Admin declares another user as creator, set it to that other user. Otherwise, use request.user user = validated_data.pop('cached_creator', None) if user: validated_data['created_by'] = user potential_email = validated_data['email'] if validated_data.get('badgrapp') is None: validated_data['badgrapp'] = BadgrApp.objects.get_current(request) # Server admins are exempt from email verification requirement. They will enforce it themselves. if not request_authenticated_with_server_admin_token(request) and not validated_data['created_by'].is_email_verified(potential_email): raise serializers.ValidationError( "Issuer email must be one of your verified addresses. Add this email to your profile and try again.") staff = validated_data.pop('staff_items', []) new_issuer = super(IssuerSerializerV2, self).create(validated_data) # update staff after issuer is created new_issuer.staff_items = staff return new_issuer def update(self, instance, validated_data): validated_data.pop('cached_creator', None) if 'image' in validated_data: self.context['save_kwargs'] = dict(force_resize=True) return super(IssuerSerializerV2, self).update(instance, validated_data) def to_representation(self, instance): from backpack.api import _scrub_boolean include_staff = _scrub_boolean(self.context['request'].query_params.get('include_staff', True)) if self.fields.get('staff') and not include_staff: self.fields.pop('staff') return super(IssuerSerializerV2, self).to_representation(instance)
class EthDataSerializer(srz.Serializer): ethRate = srz.CharField(max_length=200) balance = srz.CharField(max_length=200) lastBlockData = srz.DictField(child=srz.CharField())
class DeviceNAPALMSerializer(serializers.Serializer): method = serializers.DictField()
class InterviewResultsSerializer(serializers.Serializer): interview_id = serializers.IntegerField() total = serializers.CharField() levels = serializers.DictField()
class UserProfileSerializer(DynamicFieldsSerializer): favourite_products = serializers.DictField() exclude_ingrs = serializers.DictField() include_ingrs = serializers.DictField() exclude_ingrs_groups = serializers.DictField() include_ingrs_groups = serializers.DictField() class Meta: model = UserProfile fields = [ 'favourite_products', 'exclude_ingrs', 'include_ingrs', 'exclude_ingrs_groups', 'include_ingrs_groups' ] def to_representation(self, instance): output = {} # The representation for /users/{id}/favourites. # In this request, 'self.fields' contain only 'favourite_products' field. if 'favourite_products' in self.fields: output['favourite_products'] = ProfileHandler.get_values( instance.profile.favourite_products, Product) # The representation for /users/{id}/ingrs. # In this request, 'self.fields' contain the rest of fields. elif 'exclude_ingrs' in self.fields: output['exclude_ingrs'] = ProfileHandler.get_values( instance.profile.exclude_ingrs, Ingredient) output['include_ingrs'] = ProfileHandler.get_values( instance.profile.include_ingrs, Ingredient) output['exclude_ingrs_groups'] = ProfileHandler.get_values( instance.profile.exclude_ingrs_groups, IngredientsGroup) output['include_ingrs_groups'] = ProfileHandler.get_values( instance.profile.exclude_ingrs_groups, IngredientsGroup) return output def update(self, instance, validated_data): profile = UserProfile.objects.get(user=instance.pk) fileds = { 'favourite_products': { 'field': profile.favourite_products, 'model': Product }, 'exclude_ingrs': { 'field': profile.exclude_ingrs, 'model': Ingredient }, 'include_ingrs': { 'field': profile.exclude_ingrs, 'model': Ingredient }, 'exclude_ingrs_groups': { 'field': profile.exclude_ingrs_groups, 'model': Ingredient }, 'include_ingrs_groups': { 'field': profile.include_ingrs_groups, 'model': Ingredient } } for field, data in validated_data.items(): data |= fileds[field] ProfileHandler.make_action(data) profile.save() return instance
class EditPollSerializer(serializers.ModelSerializer): length = serializers.IntegerField(required=True, min_value=0, max_value=180) question = serializers.CharField(required=True, max_length=255) allowed_choices = serializers.IntegerField(required=True, min_value=1) choices = serializers.ListField( allow_empty=False, child=serializers.DictField(), ) class Meta: model = Poll fields = ( 'length', 'question', 'allowed_choices', 'allow_revotes', 'choices', ) def validate_choices(self, choices): clean_choices = list(map(self.clean_choice, choices)) # generate hashes for added choices choices_map = {} for choice in self.instance.choices: choices_map[choice['hash']] = choice final_choices = [] for choice in clean_choices: if choice['hash'] in choices_map: choices_map[choice['hash']].update({'label': choice['label']}) final_choices.append(choices_map[choice['hash']]) else: choice.update({'hash': get_random_string(12), 'votes': 0}) final_choices.append(choice) self.validate_choices_num(final_choices) return final_choices def clean_choice(self, choice): clean_choice = { 'hash': choice.get('hash', get_random_string(12)), 'label': choice.get('label', ''), } serializer = PollChoiceSerializer(data=clean_choice) if not serializer.is_valid(): raise serializers.ValidationError( _("One or more poll choices are invalid.")) return serializer.data def validate_choices_num(self, choices): total_choices = len(choices) if total_choices < 2: raise serializers.ValidationError( _("You need to add at least two choices to a poll.")) if total_choices > MAX_POLL_OPTIONS: message = ungettext( "You can't add more than %(limit_value)s option to a single poll (added %(show_value)s).", "You can't add more than %(limit_value)s options to a single poll (added %(show_value)s).", MAX_POLL_OPTIONS) raise serializers.ValidationError(message % { 'limit_value': MAX_POLL_OPTIONS, 'show_value': total_choices }) def validate(self, data): if data['allowed_choices'] > len(data['choices']): raise serializers.ValidationError( _("Number of allowed choices can't be greater than number of all choices." )) return data def update(self, instance, validated_data): if instance.choices: self.update_choices(instance, validated_data['choices']) return super(EditPollSerializer, self).update(instance, validated_data) def update_choices(self, instance, cleaned_choices): removed_hashes = [] final_hashes = [c['hash'] for c in cleaned_choices] for choice in instance.choices: if choice['hash'] not in final_hashes: instance.votes -= choice['votes'] removed_hashes.append(choice['hash']) if removed_hashes: instance.pollvote_set.filter( choice_hash__in=removed_hashes).delete()
class NodeLogParamsSerializer(RestrictedDictSerializer): addon = ser.CharField(read_only=True) bucket = ser.CharField(read_only=True) citation_name = ser.CharField(read_only=True, source='citation.name') contributors = ser.SerializerMethodField(read_only=True) data_set = ser.CharField(read_only=True, source='dataset') destination = NodeLogFileParamsSerializer(read_only=True) figshare_title = ser.CharField(read_only=True, source='figshare.title') forward_url = ser.CharField(read_only=True) github_user = ser.CharField(read_only=True, source='github.user') github_repo = ser.CharField(read_only=True, source='github.repo') file = ser.DictField(read_only=True) filename = ser.CharField(read_only=True) kind = ser.CharField(read_only=True) folder = ser.CharField(read_only=True) folder_name = ser.CharField(read_only=True) license = ser.CharField(read_only=True, source='new_license') identifiers = NodeLogIdentifiersSerializer(read_only=True) institution = NodeLogInstitutionSerializer(read_only=True) old_page = ser.CharField(read_only=True) page = ser.CharField(read_only=True) page_id = ser.CharField(read_only=True) params_node = ser.SerializerMethodField(read_only=True) params_project = ser.SerializerMethodField(read_only=True) path = ser.CharField(read_only=True) pointer = ser.DictField(read_only=True) preprint = ser.CharField(read_only=True) preprint_provider = ser.SerializerMethodField(read_only=True) previous_institution = NodeLogInstitutionSerializer(read_only=True) source = NodeLogFileParamsSerializer(read_only=True) study = ser.CharField(read_only=True) tag = ser.CharField(read_only=True) tags = ser.CharField(read_only=True) target = NodeLogFileParamsSerializer(read_only=True) template_node = ser.DictField(read_only=True) title_new = ser.CharField(read_only=True) title_original = ser.CharField(read_only=True) updated_fields = ser.DictField(read_only=True) urls = ser.DictField(read_only=True) version = ser.CharField(read_only=True) wiki = ser.DictField(read_only=True) citation_name = ser.CharField(read_only=True, source='citation.name') institution = NodeLogInstitutionSerializer(read_only=True) def get_view_url(self, obj): urls = obj.get('urls', None) if urls: view = urls.get('view', None) if view: return view return None def get_params_node(self, obj): node_id = obj.get('node', None) if node_id: node = Node.load(node_id) return {'id': node_id, 'title': node.title} return None def get_params_project(self, obj): project_id = obj.get('project', None) if project_id: node = Node.load(project_id) return {'id': project_id, 'title': node.title} return None def get_contributors(self, obj): contributor_info = [] if is_anonymized(self.context['request']): return contributor_info contributor_ids = obj.get('contributors', None) params_node = obj.get('node', None) if contributor_ids: for contrib_id in contributor_ids: user = User.load(contrib_id) unregistered_name = None if user.unclaimed_records.get(params_node): unregistered_name = user.unclaimed_records[ params_node].get('name', None) contributor_info.append({ 'id': contrib_id, 'full_name': user.fullname, 'given_name': user.given_name, 'middle_names': user.middle_names, 'family_name': user.family_name, 'unregistered_name': unregistered_name, 'active': user.is_active }) return contributor_info def get_preprint_provider(self, obj): preprint_id = obj.get('preprint', None) if preprint_id: preprint = PreprintService.load(preprint_id) if preprint: provider = preprint.provider return {'url': provider.external_url, 'name': provider.name} return None
class SessionRecordingMetadataSerializer(serializers.Serializer): segments = serializers.ListField(required=False) start_and_end_times_by_window_id = serializers.DictField(required=False) session_id = serializers.CharField() viewed = serializers.BooleanField()
class PackageDetailsSerializer(serializers.Serializer): name = serializers.CharField() details = serializers.DictField()
class BulkEditSerializer(DocumentListSerializer): method = serializers.ChoiceField( choices=[ "set_correspondent", "set_document_type", "add_tag", "remove_tag", "modify_tags", "delete" ], label="Method", write_only=True, ) parameters = serializers.DictField(allow_empty=True) def _validate_tag_id_list(self, tags, name="tags"): if not type(tags) == list: raise serializers.ValidationError(f"{name} must be a list") if not all([type(i) == int for i in tags]): raise serializers.ValidationError( f"{name} must be a list of integers") count = Tag.objects.filter(id__in=tags).count() if not count == len(tags): raise serializers.ValidationError( f"Some tags in {name} don't exist or were specified twice.") def validate_method(self, method): if method == "set_correspondent": return bulk_edit.set_correspondent elif method == "set_document_type": return bulk_edit.set_document_type elif method == "add_tag": return bulk_edit.add_tag elif method == "remove_tag": return bulk_edit.remove_tag elif method == "modify_tags": return bulk_edit.modify_tags elif method == "delete": return bulk_edit.delete else: raise serializers.ValidationError("Unsupported method.") def _validate_parameters_tags(self, parameters): if 'tag' in parameters: tag_id = parameters['tag'] try: Tag.objects.get(id=tag_id) except Tag.DoesNotExist: raise serializers.ValidationError("Tag does not exist") else: raise serializers.ValidationError("tag not specified") def _validate_parameters_document_type(self, parameters): if 'document_type' in parameters: document_type_id = parameters['document_type'] if document_type_id is None: # None is ok return try: DocumentType.objects.get(id=document_type_id) except DocumentType.DoesNotExist: raise serializers.ValidationError( "Document type does not exist") else: raise serializers.ValidationError("document_type not specified") def _validate_parameters_correspondent(self, parameters): if 'correspondent' in parameters: correspondent_id = parameters['correspondent'] if correspondent_id is None: return try: Correspondent.objects.get(id=correspondent_id) except Correspondent.DoesNotExist: raise serializers.ValidationError( "Correspondent does not exist") else: raise serializers.ValidationError("correspondent not specified") def _validate_parameters_modify_tags(self, parameters): if "add_tags" in parameters: self._validate_tag_id_list(parameters['add_tags'], "add_tags") else: raise serializers.ValidationError("add_tags not specified") if "remove_tags" in parameters: self._validate_tag_id_list(parameters['remove_tags'], "remove_tags") else: raise serializers.ValidationError("remove_tags not specified") def validate(self, attrs): method = attrs['method'] parameters = attrs['parameters'] if method == bulk_edit.set_correspondent: self._validate_parameters_correspondent(parameters) elif method == bulk_edit.set_document_type: self._validate_parameters_document_type(parameters) elif method == bulk_edit.add_tag or method == bulk_edit.remove_tag: self._validate_parameters_tags(parameters) elif method == bulk_edit.modify_tags: self._validate_parameters_modify_tags(parameters) return attrs