class BrandSerializer(ModelSerializer): random_hero_image = URLField(max_length=600) random_normal_image = URLField(max_length=600) terms_conditions = TermConditionSerializer(many=True) privacy_policy = PrivacyPolicySerializer(many=True) return_policy = ReturnPolicySerializer(many=True) hero_images = HeroImageSerializer(many=True) normal_images = NormalImageSerializer(many=True) class Meta: model = Brand fields = '__all__'
class UserSearchSerializer(ModelSerializer): public_email = EmailField(required=False) national_code = CharField(required=False, max_length=20, allow_blank=True) profile_media = IntegerField(required=False, allow_null=True) birth_date = CharField(required=False, max_length=10, allow_blank=True) fax = CharField(required=False, allow_blank=True) telegram_account = CharField(required=False, max_length=256, allow_blank=True) description = CharField(required=False, allow_blank=True) web_site = ListField(child=URLField(required=False), required=False) phone = ListField(child=CharField(max_length=23, required=False), required=False) mobile = ListField(child=CharField(max_length=23, required=False), required=False) password = CharField(max_length=255) auth_mobile = CharField(required=False, validators=[RegexValidator('^[0][9][0-9]{9,9}$')]) class Meta: model = User fields = [ 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'password', 'date_joined', 'web_site', 'public_email', 'national_code', 'profile_media', 'birth_date', 'fax', 'telegram_account', 'description', 'phone', 'mobile', 'auth_mobile' ]
class RetreiveUrlSerializer(CreateShortUrlSerializer): url = URLField(read_only=True) short_code = CharField(required=True) class Meta: model = Url fields = ["url"]
class PostSerializer(ModelSerializer): liking_url = URLField() clean_time = CharField(source='get_clean_time') class Meta: model = Post fields = '__all__'
class JobApplicationSerializer(serializers.GeoModelSerializer): url = URLField(required=False) class Meta: model = JobApplication fields = ('id', 'title', 'company_name', 'url', 'was_referred', 'contact_name', 'salary', 'address', 'date_applied', 'geo') read_only_fields = ['id', 'date_applied']
class TikTokSerializer(Serializer): tiktok_url = URLField(max_length=512) def is_valid(self, raise_exception=False): if super().is_valid(): return 'tiktok.com' in self.data['tiktok_url'] else: return False
class CreateShortUrlSerializer(ModelSerializer): url = URLField(required=True) short_code = SerializerMethodField(read_only=True) class Meta: model = Url fields = ["url", "short_code"] def get_short_code(self, obj): short_code = shorten_id(obj.id) return short_code
class GameSerializer(ModelSerializer): """game serializer""" designer_name = StringRelatedField(source="designer", many=True, read_only=True) artist_name = StringRelatedField(source="artist", many=True, read_only=True) game_type_name = StringRelatedField(source="game_type", many=True, read_only=True) category_name = StringRelatedField(source="category", many=True, read_only=True) mechanic_name = StringRelatedField(source="mechanic", many=True, read_only=True) contained_in = PrimaryKeyRelatedField(many=True, read_only=True) implemented_by = PrimaryKeyRelatedField(many=True, read_only=True) alt_name = ListField(child=CharField(), required=False) image_url = ListField(child=URLField(), required=False) video_url = ListField(child=URLField(), required=False) external_link = ListField(child=URLField(), required=False) freebase_id = ListField(child=CharField(), required=False) wikidata_id = ListField(child=CharField(), required=False) wikipedia_id = ListField(child=CharField(), required=False) dbpedia_id = ListField(child=CharField(), required=False) luding_id = ListField(child=IntegerField(min_value=1), required=False) spielen_id = ListField(child=CharField(), required=False) bga_id = ListField(child=CharField(), required=False) class Meta: """meta""" model = Game fields = "__all__"
class SubmissionFileSerializer(DynamicModelSerializer): filename = CharField(read_only=True) url = URLField(source='file_url', read_only=True) file = FileField(max_length=None, allow_empty_file=False, write_only=True) # TODO: make submission a non-required field (for detail put) # but add a check in create that requires it (for post) # TODO: override update() to auto set the updated date # (actually should have it call the manager's update method which # does the 'auto-setting') # TODO: need to ensure unique on owner/submission/filename somehow # possibly store filename in db and make unique constraint with it class Meta: model = SubmissionFile fields = ( 'id', 'owner', 'filename', 'url', 'submission', 'created_date', 'updated_date', 'file' ) read_only_fields = ( 'owner', 'filename', 'url', 'created_date', 'updated_date' ) def create(self, validated_data): # User validation handled by DRY permissions user = self.context['request'].user # submission = Submission.objects.get(id=submission_id) submission = validated_data.pop('submission') if user != submission.submitter: raise PermissionDenied('You do not own this submission') return SubmissionFile.objects.create( validated_data, owner=user, submission=submission )
class ContentUploadSerializer(Serializer): """ A serializer class. Containing three fields: for file, for link, and for email. """ file_upload = FileField() url_upload = URLField() email_upload = EmailField() class Meta: """Meta data.""" fields = ['file_uploaded', 'url_upload', 'email_upload']
class ArticleSerializer(ModelSerializer): comments = URLField(source='get_comments') class Meta: model = Article fields = [ 'title', 'slug', 'content', 'status', 'comments', 'create_user', 'create_date', 'update_date', 'update_user', ]
class FacilityCreateBodySerializer(Serializer): country = CharField(required=True) name = CharField(required=True, max_length=200) address = CharField(required=True, max_length=200) ppe_product_types = ListField(required=False, child=CharField(required=True, max_length=50)) ppe_contact_phone = CharField(required=False, max_length=20) ppe_contact_email = CharField(required=False) ppe_website = URLField(required=False) def validate_country(self, value): try: return get_country_code(value) except ValueError as ve: raise ValidationError(ve)
class MapRequestSerializer(Serializer): basemap = CharField(max_length=200, allow_blank=True, allow_null=True, required=False) case_insensitive = NullBooleanField(required=False) end_user_timezone = CharField(max_length=200, allow_null=True, required=False) map_format = ChoiceField(["all", "geojson", "gif", "jpg", "png", "xy"], required=False) text = CharField(max_length=1e10, trim_whitespace=True, allow_null=True, required=False) url = URLField(allow_null=True, required=False)
class SocialProfileSerializer(Serializer): username = CharField(required=False) bio = CharField(required=False) type_id = CharField(required=False) typeId = CharField(source='type_id', required=False) url = URLField(required=False) type_name = CharField(required=False) typeName = CharField(source='type_name', required=False) network = CharField(required=False) type = CharField(source='network', required=False) user_id = CharField(required=False) id = CharField(source='user_id', required=False) def to_representation(self, obj): return { 'username': obj.username, 'bio': obj.bio, 'typeId': obj.type_id, 'url': obj.url, 'typeName': obj.type_name, 'type': obj.network, 'id': obj.user_id, # 'followers': 0 # 'following': 0 } class Meta: model = SocialProfile fields = ( 'username', 'bio', 'type_id', 'url', 'type_name', 'network', 'user_id', 'id', 'type', 'typeName', 'typeId', )
class FeedEditSerializer(ModelSerializer): username = SerializerMethodField() picture = URLField(source='get_picture', read_only=True) class Meta: model = Feed fields = [ 'id', 'user', 'picture', 'username', 'date', 'parent', 'post', ] def get_username(self, obj): return str(obj.user.username) def __str__(self): return self.user.username
class ArticleDemoThumbSerializer(ModelSerializer): """ Maps Article model to DemoThumb component """ title = CharField(source='name') url = URLField(source='get_absolute_url') src = SerializerMethodField() def get_src(self, obj): """ Get src returns url to image for src field """ image_field = getattr(obj, self.Meta.thumbnail_source) if image_field: thumbnailer = get_thumbnailer(image_field) thumbnail_options = {'size': self.Meta.thumbnail_size} if (hasattr(self.Meta, 'thumbnail_crop') and self.Meta.thumbnail_crop): thumbnail_options['crop'] = True try: return thumbnailer.get_thumbnail(thumbnail_options).url except InvalidImageFormatError: return '' else: return '' class Meta: model = Article fields = ( 'title', 'src', 'url', ) thumbnail_size = (366, 236) thumbnail_crop = True thumbnail_source = 'image'
class PhotoSerializer(Serializer): photo_type = CharField(required=False) type = CharField(source='photo_type', required=False) type_id = CharField(required=False) typeId = CharField(source='type_id', required=False) type_name = CharField(required=False) typeName = CharField(source='type_name', required=False) is_primary = BooleanField(required=False) isPrimary = BooleanField(source='is_primary', required=False) url = URLField(required=False) def to_representation(self, obj): return { 'type': obj.photo_type, 'typeId': obj.type_id, 'typeName': obj.type_name, 'isPrimary': obj.is_primary, 'url': obj.url, } class Meta: model = Photo fields = ( 'photo_type', 'type_id', 'type_name', 'is_primary', 'url', 'type', 'typeId', 'typeName', 'isPrimary', )
class TestSerializer(Serializer): # pylint: disable=abstract-method boolean_field = BooleanField() char_field = CharField() choice_field = ChoiceField([]) date_field = DateField() date_time_field = DateTimeField() decimal_field = DecimalField(1, 1) dict_field = DictField() duration_field = DurationField() email_field = EmailField() file_field = FileField() file_path_field = FilePathField('') float_field = FloatField() image_field = ImageField() integer_field = IntegerField() ip_address_field = IPAddressField() json_field = JSONField() string_list_field = ListField(child=CharField()) int_list_field = ListField(child=IntegerField()) int_list_list_field = ListField( child=ListField( child=IntegerField(), ), ) multiple_choice_field = MultipleChoiceField([]) null_boolean_field = NullBooleanField() regex_field = RegexField('') slug_field = SlugField() time_field = TimeField() url_field = URLField() uuid_field = UUIDField() nullable_char_field = CharField(allow_null=True) nullable_char_listfield = ListField( child=CharField(allow_null=True), ) write_only_field = CharField(write_only=True)
class UserProfileSerializer(ModelSerializer): picture = URLField(source='get_picture', read_only=True) class Meta: model = Profile fields = ['location', 'url', 'job_title', 'picture']
class RPMPackageSerializer(ModelSerializer): dist_git_url = URLField(required=False, max_length=200) class Meta: model = RPMPackage fields = "__all__"
class ContainerSerializer(ModelSerializer): dist_git_url = URLField(required=False, max_length=200) class Meta: model = Container fields = "__all__"
class UserSerializer(ModelSerializer): public_email = EmailField(required=False) national_code = CharField(required=False, max_length=20, allow_blank=True) profile_media = IntegerField(required=False, allow_null=True) birth_date = CharField(required=False, max_length=10, allow_blank=True) fax = CharField(required=False, allow_blank=True) telegram_account = CharField(required=False, max_length=256, allow_blank=True) description = CharField(required=False, allow_blank=True) web_site = ListField(child=URLField(required=False), required=False) phone = ListField(child=CharField(max_length=23, required=False), required=False) mobile = ListField(child=CharField(max_length=23, required=False), required=False) password = CharField(max_length=255) auth_mobile = CharField(required=False, validators=[RegexValidator('^[0][9][0-9]{9,9}$')]) class Meta: model = User fields = [ 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'password', 'date_joined', 'web_site', 'public_email', 'national_code', 'profile_media', 'birth_date', 'fax', 'telegram_account', 'description', 'phone', 'mobile', 'auth_mobile' ] def create(self, validated_data): validated_data['username'] = validated_data['username'].lower() validated_data['username'] = validated_data['username'].replace( '.', '') user_validated_data = self.get_user_validated_args(**validated_data) user = User.objects.create(**user_validated_data) user.set_password(validated_data['password']) user.save() profile_validated_data = self.get_profile_validated_data( **validated_data) profile = Profile.objects.get(profile_user=user) # set validated data to profile object for key in profile_validated_data: setattr(profile, key, validated_data.get(key)) profile.save() user_strength = StrengthStates.objects.get(strength_user=user) # check for first & last name strength rate if validated_data.get('first_name') is not None and validated_data.get( 'last_name') is not None: profile.profile_strength += 5 profile.save() user_strength.first_last_name_obtained = True # check for profile media strength rate if 'profile_media' in profile_validated_data: profile.profile_strength += 10 profile.save() user_strength.profile_media_obtained = True user_strength.registration_obtained = True user_strength.save() # add user to default exchange add_user_to_default_exchange(user) return user def update(self, instance, validated_data): user = User.objects.get(pk=instance.id) profile = Profile.objects.get(profile_user=user) user_validated_data = self.get_user_validated_args(**validated_data) try: user_strength = StrengthStates.objects.get(strength_user=user) except StrengthStates.DoesNotExist: user_strength = StrengthStates.objects.create(strength_user=user) # check for first name strength rate if 'first_name' in user_validated_data and user_validated_data[ 'first_name'] != '': user.first_name = user_validated_data['first_name'] if (user.first_name is None or user.first_name == '') and (user.last_name is not None or user.last_name != ''): profile.profile_strength += 5 user_strength.first_last_name_obtained = True # check for last name strength rate if 'last_name' in user_validated_data and user_validated_data[ 'last_name'] != '': user.last_name = user_validated_data['last_name'] if (user.last_name is None or user.last_name == '') and (user.first_name is not None or user.first_name != ''): profile.profile_strength += 5 user_strength.first_last_name_obtained = True # set validated data to user object for key in user_validated_data: if key != 'first_name' and key != 'last_name': setattr(user, key, user_validated_data.get(key)) if 'password' in validated_data: user.set_password(validated_data['password']) user.save() profile_validated_data = self.get_profile_validated_data( **validated_data) # check for profile media strength rate if 'profile_media' in profile_validated_data and profile_validated_data['profile_media'] != '' and \ profile_validated_data['profile_media'] is not None: profile.profile_media = profile_validated_data['profile_media'] if profile.profile_media == '' or profile.profile_media is None: profile.profile_strength += 10 user_strength.profile_media_obtained = True # set validated data to profile object for key in profile_validated_data: if key != 'profile_media': setattr(profile, key, validated_data.get(key)) profile.save() user_strength.save() return user @staticmethod def validate_first_name(value): if len(value) > 20: error = { 'message': "maximum length for first name is 20 character" } raise ValidationError(error) return value @staticmethod def validate_email(value): if value is None: error = {'message': "email field is required"} raise ValidationError(error) elif len(value) > 0: user_count = User.objects.filter(email=value).count() if user_count == 0: return value error = {'message': "email already exist"} raise ValidationError(error) error = {'message': "email can not be blank"} raise ValidationError(error) @staticmethod def validate_last_name(value): if len(value) > 20: error = {'message': "maximum length for last name is 20 character"} raise ValidationError(error) return value @staticmethod def validate_username(value): if len(value) < 5: error = {'message': "minimum length for last name is 5 character"} raise ValidationError(error) if len(value) > 32: error = {'message': "minimum length for last name is 5 character"} raise ValidationError(error) return value @staticmethod def validate_password(value): if len(value) < 8: error = {'message': "minimum length for password is 8 character"} raise ValidationError(error) return value def get_user_validated_args(self, **kwargs): user_kwargs = {} if 'username' in kwargs: user_kwargs['username'] = kwargs['username'] if 'first_name' in kwargs: user_kwargs['first_name'] = kwargs['first_name'] if 'last_name' in kwargs: user_kwargs['last_name'] = kwargs['last_name'] if 'email' in kwargs: user_kwargs['email'] = kwargs['email'] return user_kwargs def get_profile_validated_data(self, **kwargs): profile_kwargs = {} if 'public_email' in kwargs: profile_kwargs['public_email'] = kwargs['public_email'] if 'national_code' in kwargs: profile_kwargs['national_code'] = kwargs['national_code'] if 'profile_media' in kwargs: profile_kwargs['profile_media'] = kwargs['profile_media'] if 'birth_date' in kwargs: profile_kwargs['birth_date'] = kwargs['birth_date'] if 'fax' in kwargs: profile_kwargs['fax'] = kwargs['fax'] if 'telegram_account' in kwargs: profile_kwargs['telegram_account'] = kwargs['telegram_account'] if 'description' in kwargs: profile_kwargs['description'] = kwargs['description'] if 'web_site' in kwargs: profile_kwargs['web_site'] = kwargs['web_site'] if 'phone' in kwargs: profile_kwargs['phone'] = kwargs['phone'] if 'mobile' in kwargs: profile_kwargs['mobile'] = kwargs['mobile'] if 'auth_mobile' in kwargs: profile_kwargs['auth_mobile'] = kwargs['auth_mobile'] return profile_kwargs
class ShortenedLinkResponseSerializer(Serializer): shortened_url = URLField( help_text="A shortened link on the `shares.cc` domain.")
class Shipment(ShipmentDetails, ShipmentRequest): selected_rate_id = UUIDField(required=True, help_text="The shipment selected rate.") tracking_url = URLField(required=False, help_text="The shipment tracking url")
class ShipmentContent(Serializer): # Process result properties status = ChoiceField( required=False, default=ShipmentStatus.created.value, choices=SHIPMENT_STATUS, help_text="The current Shipment status") carrier_name = CharField(required=False, allow_blank=True, allow_null=True, help_text="The shipment carrier") carrier_id = CharField(required=False, allow_blank=True, allow_null=True, help_text="The shipment carrier configured identifier") label = CharField(required=False, allow_blank=True, allow_null=True, help_text="The shipment label in base64 string") tracking_number = CharField(required=False, allow_blank=True, allow_null=True, help_text="The shipment tracking number") shipment_identifier = CharField(required=False, allow_blank=True, allow_null=True, help_text="The shipment carrier system identifier") selected_rate = Rate(required=False, allow_null=True, help_text="The shipment selected rate") selected_rate_id = CharField(required=False, allow_blank=True, allow_null=True, help_text="The shipment selected rate.") rates = Rate(many=True, required=False, allow_null=True, help_text="The list for shipment rates fetched previously") tracking_url = URLField(required=False, allow_blank=True, allow_null=True, help_text="The shipment tracking url") service = CharField(required=False, allow_blank=True, allow_null=True, help_text="The selected service") # Request properties shipper = Address(required=True, help_text=""" The address of the party Origin address (ship from) for the **shipper**<br/> Destination address (ship to) for the **recipient** """) recipient = Address(required=True, help_text=""" The address of the party Origin address (ship from) for the **shipper**<br/> Destination address (ship to) for the **recipient** """) parcels = Parcel(many=True, required=True, help_text="The shipment's parcels") services = StringListField(required=False, allow_null=True, default=[], help_text=""" The carriers services requested for the shipment. Please consult [the reference](#operation/references) for specific carriers services.<br/> Note that this is a list because on a Multi-carrier rate request you could specify a service per carrier. """) options = PlainDictField(required=False, allow_null=True, help_text=""" The options available for the shipment.<br/> Please consult [the reference](#operation/references) for additional specific carriers options. """) payment = Payment(required=False, allow_null=True, help_text="The payment details") customs = Customs(required=False, allow_null=True, help_text=""" The customs details.<br/> Note that this is required for the shipment of an international Dutiable parcel. """) reference = CharField(required=False, allow_blank=True, allow_null=True, help_text="The shipment reference") label_type = ChoiceField(required=False, choices=LABEL_TYPES, allow_blank=True, allow_null=True, help_text="The shipment label file type.") carrier_ids = StringListField(required=False, allow_null=True, default=[], help_text=""" The list of configured carriers you wish to get rates from. *Note that the request will be sent to all carriers in nothing is specified* """) meta = PlainDictField(required=False, allow_null=True, help_text="provider specific metadata") created_at = CharField(required=True, help_text=""" The shipment creation date Date Format: `YYYY-MM-DD` """) test_mode = BooleanField(required=True, help_text="Specified whether it was created with a carrier in test mode") messages = Message(required=False, many=True, default=[], help_text="The list of note or warning messages")
class CommentSerializer(Serializer): id = IntegerField() url = URLField() text = CharField() author = JSONField()
class PurchaseCountSerializer(Serializer): class Meta: read_only_fields = ['beverage_type', 'count'] beverage_type = URLField() count = IntegerField()
class FeedSerializer(ModelSerializer): url = URLField(source='feed_url', required=False) feed_url = URLField(required=False) contactid = PrimaryKeyRelatedField(source='contact', queryset=Contact.objects.all(), required=False, write_only=False) contact = PrimaryKeyRelatedField(queryset=Contact.objects.all(), required=False, write_only=False) listid = PrimaryKeyRelatedField(source='list_in', queryset=MediaList.objects.all(), required=False, write_only=False) list_in = PrimaryKeyRelatedField(queryset=MediaList.objects.all(), required=False, write_only=False) publicationid = PrimaryKeyRelatedField(source='publication', queryset=Publication.objects.all(), required=False, write_only=False) publication = PrimaryKeyRelatedField(queryset=Publication.objects.all(), required=False, write_only=False) validfeed = BooleanField(source='valid_feed', required=False) valid_feed = BooleanField(required=False) running = BooleanField(required=False) def to_representation(self, obj): has_data = False included = {} if isinstance(obj, dict): if 'data' in obj and 'included' in obj: has_data = True included = obj['included'] obj = obj['data'] feed = { 'id': obj.pk, 'type': 'feeds', 'createdby': obj.created_by and obj.created_by.pk, 'created': obj.created, 'updated': obj.updated, 'url': obj.feed_url, 'contactid': obj.contact and obj.contact.pk, 'publicationid': obj.publication and obj.publication.pk, 'validfeed': obj.valid_feed, 'running': obj.running, } if has_data: return { 'data': feed, 'included': included, } return feed def create(self, data): contact = None publication = None if 'contact' in data: contact = data.pop('contact') if 'publication' in data: publication = data.pop('publication') feed = Feed.objects.create(**data) if contact: feed.contact = contact if publication: feed.publication = publication user = None request = self.context.get('request') if request and hasattr(request, 'user'): user = request.user feed.created_by = user feed.save() return feed class Meta: model = Feed fields = ( 'feed_url', 'contact', 'list_in', 'publication', 'valid_feed', 'running', 'contactid', 'listid', 'publicationid', 'validfeed', 'url', )