class ExposedServiceSerializer(EmbeddedDocumentSerializer): component = SlugField(source='group.name') service = SlugField(source='service_name') class Meta: model = ServiceReference fields = ('component', 'service')
class ComponentLinkSerializer(EmbeddedDocumentSerializer): src_component = SlugField(source='from_component.name') dest_component = SlugField(source='to_service.group.name') dest_service = SlugField(source='to_service.service_name') class Meta: model = ComponentLink fields = ('src_component', 'dest_component', 'dest_service')
class DocgiTokenObtainPairSerializer(TokenObtainSerializer): workspace = SlugField(required=True) @classmethod def get_token(cls, user, **kwargs): token = RefreshToken.for_user(user) for k, v in kwargs.items(): token[k] = v return token def validate(self, attrs): workspace = attrs.pop("workspace") data = super().validate(attrs) try: workspace_member = WorkspaceMember.objects.get( user_id=self.user.id, workspace__name__iexact=workspace) except WorkspaceMember.DoesNotExist: raise AuthenticationFailed() refresh = self.get_token( self.user, **{ KEY_WORKSPACE_NAME_OBTAIN_TOKEN: workspace_member.workspace_id, KEY_WORKSPACE_ROLE_OBTAIN_TOKEN: workspace_member.role }) data["token"] = str(refresh.access_token) return data
class FeedbackSerializer(ModelSerializer): user = UserDetailSerializer(read_only=True) timestamp = DateTimeField(read_only=True) shopSlug = SlugField(write_only=True) def validate_shopSlug(self, slug): shop_qs = Shop.objects.filter(slug=slug) if shop_qs.exists() and shop_qs.count() == 1: return shop_qs.first() raise ValidationError( 'Sorry cannot find the shop you are commentig on') def create(self, validate_data): shopSlug = validate_data['shopSlug'] shop = validate_data['shopSlug'] content = validate_data["content"] user = self.context['request'].user # print ("hello") # print (self.context['request'].COOKIES['token']) # print(self.context['request'].META['REMOTE_ADDR']) return Feedback.objects.create(user=user, shop=shop, content=content) class Meta: model = Feedback fields = ['shopSlug', 'user', 'content', 'timestamp']
class MembershipModelSerializer(ModelSerializer): price = DecimalField(write_only=True, max_digits=100, decimal_places=2) slug = SlugField(read_only=True) class Meta: model = Membership fields = ("membership_type", "slug", "price") def create(self, validated_data): return Membership.objects.create(**validated_data)
def property_field(max_length=256, required=True): """Returns a property field. :param max_length: Max length of field :type max_length: int :param required: Is this field required? :type required: bool :return: SlugField :rtype: SlugField """ return SlugField(max_length=max_length, required=required)
class ProductSerializer(ModelSerializer): category_slug = SlugField(source='category.slug', read_only=True) image = SerializerMethodField('get_image_url') class Meta: model = Product fields = ('id', 'category', 'category_slug', 'name', 'description', 'price', 'image') read_only_fields = ('id', ) def get_image_url(self, obj): return self.context['request'].build_absolute_uri(obj.image_url)
class CommentCreateSerializer(ModelSerializer): type = CharField(required=False, write_only=True) slug = SlugField(write_only=True) parent_id = IntegerField(required=False) class Meta: model = Comment fields = [ "id", "type", "slug", "parent_id", "created_at", "content", ] def validate(self, data): model_type = data.get("type", "post") model_qs = ContentType.objects.filter(model=model_type) if not model_qs.exists() or model_qs.count() != 1: raise ValidationError("Invalid content type") SomeModel = model_qs.first().model_class() slug = data.get("slug") obj_qs = SomeModel.objects.filter(slug=slug) if not obj_qs.exists() or obj_qs.count() != 1: raise ValidationError("Content type and slug do not match") parent_id = data.get("parent_id") if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if not parent_qs.exists() or parent_qs.count() != 1: raise ValidationError( "This is not a valid parent for this content") return data def create(self, validated_data): content = validated_data.get("content") user = self.context["user"] model_type = validated_data.get("type", "post") slug = validated_data.get("slug") parent_id = validated_data.get("parent_id") parent_obj = Comment.objects.filter( id=parent_id).first() if parent_id else None comment = Comment.objects.create_by_model_type(model_type, slug, content, user, parent_obj) return comment
class ForgotPasswordSerializer(Serializer): email = EmailField() workspace = SlugField() client_origin = CharField(allow_blank=False) def validate(self, attrs): email = attrs.get("email") workspace = attrs.get("workspace") checker = WorkspaceMember.objects.filter(workspace=workspace, user__email__exact=email) if not checker.exists(): raise ValidationError({ "email": "Workspace not exist or you are not member of this workspace" }) return attrs def create(self, validated_data): email = validated_data.get("email") workspace = validated_data.get("workspace") client_origin = validated_data.get("client_origin") user = User.objects.get(email__exact=email) reset_token = DocgiTokenObtainPairSerializer.get_token( user=user, is_reset=True, **{KEY_WORKSPACE_NAME_OBTAIN_TOKEN: workspace}) models.ResetPasswordToken.objects.create(user=user, token=reset_token) reset_link = urljoin(client_origin, f"{FRONTEND_URL_RESET_PASS}?token={reset_token}") context = dict(email=email, reset_link=reset_link, workspace=workspace) return send_mail( subject="Forgot password", email=email, text_template_path="email/forgot_password/forgot_password.txt", html_template_path="email/forgot_password/forgot_password.html", context=context) def to_representation(self, status): return {"send": status}
class TeamSerializer(ModelSerializer): slug = SlugField( required=False, validators=[UniqueValidator(queryset=Team.objects.all())], ) members = MembershipSerializer(source='membership_set', many=True, read_only=True) invitations = InvitationSerializer(many=True, read_only=True, source='pending_invitations') dashboard_url = ReadOnlyField() class Meta: model = Team fields = ('id', 'name', 'slug', 'members', 'invitations', 'dashboard_url') def create(self, validated_data): team_name = validated_data.get("name", None) validated_data['slug'] = validated_data.get("slug", get_next_unique_team_slug(team_name)) return super().create(validated_data)
class PostCommentsCreateSerializer(ModelSerializer): user = UserDetailSerializer(read_only=True) type = CharField(required=False, write_only=True) slug = SlugField(write_only=True) parent_id = IntegerField(required=False) class Meta: model = Comments fields = [ 'id', 'user', 'type', 'slug', 'parent_id', 'content', 'timestamp' ] def validate(self, data): model_type = data.get("type", "posts") model_qs = ContentType.objects.filter(model=model_type) if not model_qs.exists() or model_qs.count() != 1: raise ValidationError("This is not valid content type") someModel = model_qs.first().model_class() slug = data.get("slug") obj_qs = someModel.objects.filter(slug=slug) if not obj_qs.exists() or obj_qs.count() != 1: raise ValidationError("This is not slug for comments") parent_id = data.get("parent_id") if parent_id: parent_qs = Comments.objects.filter(id=parent_id) if not parent_qs.exists() or parent_qs.count() != 1: raise ValidationError("This is not valid parent") return data def create(self, validated_data): content = validated_data.get("content") model_type = validated_data.get("type", "posts") slug = validated_data.get("slug") parent_id = validated_data.get("parent_id") parent_obj = None if parent_id: parent_obj = Comments.objects.filter(id=parent_id).first() user = self.context['user'] comment = Comments.objects.create_by_model_type(model_type, slug, content, user, parent_obj=parent_obj) return comment
class OrderSerializer(Serializer): """Serializer for order by on a query.""" model = ChoiceField([m.label for m in registry.models.values()]) prop = SlugField(max_length=256, required=True) direction = ChoiceField(['asc', 'desc']) def validate(self, data): """Custom validation. Ensure prop is a property of model. :param data: Data to validate :type data: dict """ if data['prop'] not in registry.properties(data['model']): raise ValidationError( {'prop': INVALID_PROP_STR.format(data['prop'], data['model'])}) return data
class FilterSerializer(Serializer): """Serializer for filters on a query""" model = ChoiceField([m.label for m in registry.models.values()]) prop = SlugField(max_length=256, required=True) operator = ChoiceField(OPERATORS, required=True) value = CharField(max_length=256, required=True) def validate(self, data): """Custom validation. Ensure prop is a property of the select model. :param data: Data to validate :type data: dict """ if data['prop'] not in registry.properties(data['model']): raise ValidationError( {'prop': INVALID_PROP_STR.format(data['prop'], data['model'])}) return data
class ThreadCreateSerializer(ModelSerializer): post = CharField() thread_slug = SlugField(read_only=True) class Meta: model = Thread fields = ( 'subforum', 'user', 'title', 'post', 'thread_slug', ) def create(self, validated_data): subforum = validated_data['subforum'] user = validated_data['user'] title = validated_data['title'] post = validated_data['post'] thread_obj = Thread( subforum=subforum, user=user, title=title, ) thread_obj.save() post_obj = Post( user=thread_obj.user, thread=thread_obj, content=post, ) post_obj.save() thread_slug = Thread.objects.get(id=thread_obj.id).thread_slug validated_data['thread_slug'] = thread_slug return validated_data
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 OrderSerializer(Serializer): """Serializer for order by on a query.""" model = ChoiceField([m.label for m in registry.models.values()]) prop = SlugField(max_length=256, required=True) direction = ChoiceField(['asc', 'desc'])
class FilterSerializer(Serializer): """Serializer for filters on a query""" model = ChoiceField([m.label for m in registry.models.values()]) prop = SlugField(max_length=256, required=True) operator = ChoiceField(_operators, required=True) value = CharField(max_length=256, required=True)
class SearchHistorySessionSerializer(Serializer): song = CharField(max_length=256) tiktok_id = SlugField() timestamp = DateTimeField()