Example #1
0
class UserCreateSerializer(serializers.ModelSerializer):
    avatar = HyperlinkedSorlImageField('1024', required=False)
    wallpaper = HyperlinkedSorlImageField('1024', required=False)
    team_id = serializers.IntegerField(required=False)

    class Meta:
        model = User
        fields = ('id', 'email', 'password', 'phone', 'sex', 'avatar',
                  'date_birth', 'first_name', 'last_name', 'wallpaper',
                  'team_id', 'profession')

    def create(self, validated_data):
        user = User(
            email=validated_data['email'],
            phone=validated_data.get('phone', None),
            sex=validated_data.get('sex', None),
            avatar=validated_data.get('avatar', None),
            date_birth=validated_data.get('date_birth', None),
            first_name=validated_data.get('first_name', None),
            last_name=validated_data.get('last_name', None),
            wallpaper=validated_data.get('wallpaper', None),
            profession=validated_data.get('profession', None),
        )
        user.set_password(validated_data['password'])
        user.save()
        team_id = validated_data.get('team_id', None)
        if team_id:
            RequestTeam.objects.create(team_id=team_id, user=user)
        return user

    def to_representation(self, obj):
        ret = super().to_representation(obj)
        ret.pop('password')
        return ret
Example #2
0
class ImageAssetSerializer(serializers.ModelSerializer):
    class Meta:
        model = ImageAsset
        fields = '__all__'

    thumbnail = HyperlinkedSorlImageField('128x128',
                                          options={"crop": "center"},
                                          source='image',
                                          read_only=True)

    image = HyperlinkedSorlImageField('1024')

    def to_internal_value(self, data):
        image = data['image']
        if image is not None and type(image) == str and image.startswith(
                'http'):
            data.pop('image')
        return super().to_internal_value(data)

    def to_representation(self, instance: Any) -> Any:
        representation = super().to_representation(instance)
        image: str = representation['image']
        thumbnail = representation['thumbnail']
        if image is not None and not image.startswith('http'):
            representation['image'] = 'http://localhost:8000' + image
        if thumbnail is not None and not thumbnail.startswith('http'):
            representation['thumbnail'] = 'http://localhost:8000' + thumbnail
        return representation
    def test_to_representation_no_request(self, mocked_to_representation):
        mocked_to_representation.return_value = "ORIGINAL URL"
        field = HyperlinkedSorlImageField("200")

        image = field.to_representation("URL IMAGE")

        self.assertEqual("ORIGINAL URL", image)
    def test_to_representation_no_request(self, mocked_to_representation):
        mocked_to_representation.return_value = "ORIGINAL URL"
        field = HyperlinkedSorlImageField("200")

        image = field.to_representation("URL IMAGE")

        self.assertEqual("ORIGINAL URL", image)
Example #5
0
class ImageDetailSerializer(serializers.HyperlinkedModelSerializer):
    file = HyperlinkedSorlImageField('300x400', options={"quality": 99, "format": "PNG"}, read_only=True)
    thumbnail = HyperlinkedSorlImageField('60x60', options={"quality": 99, "format": "PNG"}, source='file', read_only=True)
    
    class Meta:
        model = Image
        fields = ("id", "file", "thumbnail",)
Example #6
0
class TestModelSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = TestModel

    thumbnail = HyperlinkedSorlImageField('128x128',
                                          options={"crop": "center"},
                                          source='image',
                                          read_only=True)
    image = HyperlinkedSorlImageField('1024')
    def test_to_representation(self):
        field = HyperlinkedSorlImageField("200")
        request = self.factory.get('/api/test_model')
        field.context = {"request": request}

        image = get_thumbnail(self.image1, "200")
        expected_url = request.build_absolute_uri(image.url)
        actual_url = field.to_representation(self.image1)

        self.assertEqual(expected_url, actual_url)
    def test_to_representation(self):
        field = HyperlinkedSorlImageField("200")
        request = self.factory.get("/api/test_model")
        field.context = {"request": request}

        image = get_thumbnail(self.image1, "200")
        expected_url = request.build_absolute_uri(image.url)
        actual_url = field.to_representation(self.image1)

        self.assertEqual(expected_url, actual_url)
Example #9
0
class ProfessionUserSerializer(serializers.ModelSerializer):
    avatar = HyperlinkedSorlImageField('1024', required=False)
    wallpaper = HyperlinkedSorlImageField('1024', required=False)
    post_count = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'email', 'phone', 'sex', 'avatar', 'date_birth',
                  'first_name', 'last_name', 'wallpaper', 'post_count')

    @staticmethod
    def get_post_count(obj):
        return obj.posts.all().count()
Example #10
0
class UserSerializer(serializers.ModelSerializer):
    avatar = HyperlinkedSorlImageField('1024', required=False)
    wallpaper = HyperlinkedSorlImageField('1024', required=False)
    post_count = serializers.SerializerMethodField()
    team_owners = UserTeamSerializer(many=True)
    team_members = UserTeamSerializer(many=True)
    crystals = serializers.SerializerMethodField()
    profession = ProfessionSerializer()
    pix = serializers.SerializerMethodField()
    gag = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'email', 'password', 'phone', 'sex', 'avatar',
                  'date_birth', 'first_name', 'last_name', 'wallpaper',
                  'post_count', 'team_owners', 'team_members', 'profession',
                  'crystals', 'pix', 'gag')

    def get_pix(self, obj):
        today = date.today()
        get_sunday = (today -
                      timedelta(days=today.weekday())) - timedelta(days=1)
        crowns = Crown.objects.filter(post__user=obj,
                                      created_at__gte=get_sunday,
                                      post_type='image').order_by('type')
        if crowns:
            return crowns[0].type
        return None

    def get_gag(self, obj):
        today = date.today()
        get_sunday = (today -
                      timedelta(days=today.weekday())) - timedelta(days=1)
        crowns = Crown.objects.filter(post__user=obj,
                                      created_at__gte=get_sunday,
                                      post_type='image').order_by('type')
        if crowns:
            return crowns[0].type
        return None

    def get_crystals(self, obj):
        return obj.get_balance()

    def to_representation(self, obj):
        ret = super().to_representation(obj)
        ret.pop('password')
        return ret

    @staticmethod
    def get_post_count(obj):
        return obj.posts.all().count()
Example #11
0
class ResourceBaseSerializer(serializers.ModelSerializer):
    creator = serializers.ReadOnlyField(source='get_creator_name')
    resource_type = serializers.SerializerMethodField()
    resource_subtype = serializers.SerializerMethodField()

    # A thumbnail image, sorl options and read-only
    thumbnail = HyperlinkedSorlImageField('128x128',
                                          options={"crop": "center"},
                                          source='thumbnail_image',
                                          read_only=True)

    class Meta:
        fields = [
            'resource_type',
            'resource_subtype',
            'uuid',
            'name',
            'creator',
            'upload_date',
            'download_count',
            'description',
            'file',
            'thumbnail',
        ]

    def validate(self, attrs):
        file = attrs.get('file')
        filesize_validator(file)
        return attrs

    def get_resource_type(self, obj):
        return self.Meta.model.__name__
Example #12
0
class UserSerializer(serializers.ModelSerializer):
    # avatar = serializers.ReadOnlyField(source='get_avatar_url')
    thumbnail_avatar = HyperlinkedSorlImageField(
        '100x100',
        options={"crop": "center"},
        source='avatar',
        read_only=True
    )
    fio = serializers.ReadOnlyField()
    # emails = EmailSerializer(source='emailaddress_set', many=True)

    class Meta:
        model = User
        fields = (
            'username',
            'email',
            # 'invites',
            'fio',
            'first_name',
            'middle_name',
            'last_name',
            'avatar',
            'role',
            'last_login',
            'date_joined',
            'account_type',
            'language',
            'thumbnail_avatar'
        )
Example #13
0
class ProfileRetrieveUpdateSerializer(ModelSerializer):
    # A thumbnail image, sorl options and read-only
    thumbnail = HyperlinkedSorlImageField('75x75',
                                          options={"crop": "center"},
                                          source='profile_image',
                                          read_only=True)

    # A larger version of the image, allows writing
    # profile_image = HyperlinkedSorlImageField('1024')

    class Meta:
        model = Profile
        fields = [
            'id',
            'first_name',
            'last_name',
            'name',
            'bio',
            'thumbnail',
            'profile_image',
            'width_field',
            'height_field',
        ]
        read_only_fields = [
            'thumbnail',
            'profile_image',
            'name',
            'width_field',
            'height_field',
        ]
Example #14
0
class PhotoSerializerForCreate(HyperlinkedModelSerializer):
    album = serializers.PrimaryKeyRelatedField(
        queryset=Album.objects.all(),
    )
    thumbnail = HyperlinkedSorlImageField(
        '128x128',
        options={'crop': 'center'},
        source='image',
        read_only=True
    )

    class Meta:
        model = Photo
        fields = (
            'id',
            'album',
            'image',
            'thumbnail',
        )
        read_only_fields = (
            'id',
        )

    def create(self, validated_data):
        photo = Photo.objects.create(
            album=validated_data['album'],
            image=validated_data['image'],
        )
        photo.save()
        return photo
Example #15
0
class UserMeSerializer(serializers.ModelSerializer):
    is_staff = serializers.ReadOnlyField()
    avatar = HyperlinkedSorlImageField('100')

    class Meta:
        model = User
        fields = ("id", "email", "nickname", "avatar", 'is_staff')
Example #16
0
class PostUserSerializer(serializers.ModelSerializer):
    image = HyperlinkedSorlImageField('1024', required=False)

    class Meta:
        model = Post
        fields = ('id', 'title', 'description', 'video_file', 'image',
                  'image_width', 'image_height', 'views', 'comment_status')
Example #17
0
class GallerySerializer(serializers.ModelSerializer):
    thumbnail = HyperlinkedSorlImageField('512x512',
                                          options={"crop": "center"},
                                          source='image',
                                          read_only=True)

    class Meta:
        model = Gallery
        fields = ('id', 'image', 'thumbnail')
Example #18
0
class ImageGetViewSerializer(serializers.ModelSerializer):
    """
    Serializer for manga edit view page
    """
    image = HyperlinkedSorlImageField('100')

    class Meta:
        model = MangaImage
        fields = ('id', 'sort_index', 'image')
Example #19
0
class ImageSerializer(TaggitSerializer, serializers.ModelSerializer):
    tags = TagListSerializerField()
    thumbnail = HyperlinkedSorlImageField('220x220',
                                          options={"crop": "center"},
                                          source='image',
                                          read_only=True)

    class Meta:
        model = Image
        fields = ['pk', 'title', 'image', 'quote', 'tags', 'thumbnail']
Example #20
0
class MangaSerializer(serializers.ModelSerializer):
    create_by_user = serializers.HiddenField(
        default=serializers.CurrentUserDefault(), )
    poster = HyperlinkedSorlImageField('720')

    class Meta:
        model = Manga
        fields = [
            'id', 'english_name', 'descriptions', 'slug', 'poster', 'rating',
            'is_promoted', 'artists', 'create_by_user'
        ]
Example #21
0
class RatingPost(BasePostSerializer):
    user = UserPostSerializer(many=False)
    image = HyperlinkedSorlImageField('1024', required=False)
    crown = serializers.IntegerField()
    crystals = serializers.IntegerField()

    class Meta:
        model = Post
        fields = ('id', 'title', 'description', 'video_file', 'image',
                  'image_width', 'image_height', 'views', 'user', 'crown',
                  'crystals')
Example #22
0
class LessonForEnrollSerializer(serializers.ModelSerializer):
    """
    используеться в get_last_lessons
    """
    # pages = PageSerializer(many=True, read_only=True)
    code_errors = JSONField()
    content = JSONField()
    thumbnail_picture = HyperlinkedSorlImageField('100x100',
                                                  options={"crop": "center"},
                                                  source='picture',
                                                  read_only=True)
    thumbnail_picture_big = HyperlinkedSorlImageField(
        '250x250',
        options={"crop": "center"},
        source='picture',
        read_only=True)
    tag = TagSerializer(many=True)

    class Meta:
        model = Lesson
Example #23
0
class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = '__all__'

    avatar = HyperlinkedSorlImageField('256x256',
                                       options={
                                           "crop": "center",
                                           "quality": 85
                                       },
                                       source='image',
                                       read_only=True)
Example #24
0
class PageBlocksSerializer(serializers.ModelSerializer):
    buttons = ButtonSerializer(read_only=True, many=True)
    original = serializers.ImageField(source='image')

    # def get_content_html(self, obj):
    #     return (build_absolute_img_url(self, obj.content_html))

    class Meta:
        model = PageBlock
        fields = '__all__'

    thumbnail = HyperlinkedSorlImageField('512x512',
                                          options={"quality": 85},
                                          source='image',
                                          read_only=True)
class PersonSerializer(MinimalPersonSerializer):
    class Meta:
        model = people.models.Person
        fields = (
            "id",
            "url",
            "name",
            "other_names",
            "identifiers",
            "honorific_prefix",
            "honorific_suffix",
            "sort_name",
            "email",
            "gender",
            "birth_date",
            "death_date",
            "versions",
            "contact_details",
            "links",
            "memberships",
            "images",
            "extra_fields",
            "thumbnail",
        )

    contact_details = ContactDetailSerializer(many=True, read_only=True)
    identifiers = IdentifierSerializer(many=True, read_only=True)
    links = LinkSerializer(many=True, read_only=True)
    other_names = OtherNameSerializer(many=True, read_only=True)
    images = ImageSerializer(many=True, read_only=True, default=[])

    versions = JSONSerializerField(read_only=True)

    memberships = MembershipSerializer(many=True, read_only=True)

    extra_fields = PersonExtraFieldSerializer(many=True,
                                              read_only=True,
                                              source="extra_field_values")

    thumbnail = HyperlinkedSorlImageField(
        "300x300",
        options={"crop": "center"},
        source="primary_image",
        read_only=True,
    )
Example #26
0
class GalleryPhotoSerializer(serializers.ModelSerializer):
    original = serializers.ImageField(source='image')
    originalTitle = serializers.CharField(source='title')
    thumbnailTitle = serializers.CharField(source='title')

    class Meta:
        model = GalleryPhoto
        fields = ('id', 'original', 'thumbnail', 'title', 'originalTitle',
                  'thumbnailTitle')
        # fields = '__all__'

    thumbnail = HyperlinkedSorlImageField('250x100',
                                          options={
                                              "crop": "center",
                                              "quality": 85
                                          },
                                          source='image',
                                          read_only=True)
class PersonSerializer(MinimalPersonSerializer):
    class Meta:
        model = popolo_models.Person
        fields = (
            'id',
            'url',
            'name',
            'other_names',
            'identifiers',
            'honorific_prefix',
            'honorific_suffix',
            'sort_name',
            'email',
            'gender',
            'birth_date',
            'death_date',
            'versions',
            'contact_details',
            'links',
            'memberships',
            'images',
            'extra_fields',
            'thumbnail',
        )

    contact_details = ContactDetailSerializer(many=True, read_only=True)
    identifiers = IdentifierSerializer(many=True, read_only=True)
    links = LinkSerializer(many=True, read_only=True)
    other_names = OtherNameSerializer(many=True, read_only=True)
    images = ImageSerializer(many=True, read_only=True, source='extra.images')

    versions = JSONSerializerField(source='extra.versions', read_only=True)

    memberships = MembershipSerializer(many=True, read_only=True)

    extra_fields = PersonExtraFieldSerializer(
        many=True, read_only=True, source='extra_field_values')

    thumbnail = HyperlinkedSorlImageField(
            '300x300',
            options={"crop": "center"},
            source='extra.primary_image',
            read_only=True
        )
class PersonSerializer(MinimalPersonSerializer):
    class Meta:
        model = people.models.Person
        fields = (
            "id",
            "url",
            "name",
            "other_names",
            "identifiers",
            "honorific_prefix",
            "honorific_suffix",
            "sort_name",
            "email",
            "gender",
            "birth_date",
            "death_date",
            "versions",
            "links",
            "memberships",
            "images",
            "thumbnail",
            "favourite_biscuit",
        )

    identifiers = IdentifierSerializer(many=True, read_only=True)
    links = LinkSerializer(many=True, read_only=True)
    other_names = OtherNameSerializer(many=True, read_only=True)
    images = ImageSerializer(many=True, read_only=True, default=[])
    email = serializers.SerializerMethodField()

    versions = JSONSerializerField(read_only=True)

    memberships = MembershipSerializer(many=True, read_only=True)

    thumbnail = HyperlinkedSorlImageField(
        "300x300",
        options={"crop": "center"},
        source="primary_image",
        read_only=True,
    )

    def get_email(self, obj):
        return obj.get_email
Example #29
0
class UserSerializer(CountryFieldMixin, ModelSerializer):
    profile_thumbnail = HyperlinkedSorlImageField(
        '512x512',
        source='profile_image',
        options={'crop': 'center'},
        read_only=True,
    )
    proficiency = ProficiencySerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = (
            'username',
            'name',
            'nationality',
            'profile_thumbnail',
            'preferred_language',
            'is_expert',
            'proficiency',
        )
Example #30
0
class CampaignListSerializer(EnumSupportSerializerMixin, ModelSerializer):
    creator = SerializerMethodField()

    # A thumbnail image, sorl options and read-only
    thumbnail = HyperlinkedSorlImageField(
        '500x500',
        options={"crop": "center"},
        source='image',
        read_only=True
    )


    class Meta:
        model = Campaign
        fields = [
            'id',
            'title',
            'creator',
            'start_time',
            'end_time',
            'description',
            'thumbnail',
            'image',
            'width_field',
            'height_field',
        ]

    read_only_fields = [
        'thumbnail',
        'image',
        'width_field',
        'height_field',
    ]

    def get_creator(self, obj):
        return CampaignPartyRelation.objects.get(
            campaign=obj,
            type=CampaignPartyRelationType.CREATOR,
        ).content_object.name
Example #31
0
class ChildSerializer(ModelSerializer):
    assigned_class = serializers.PrimaryKeyRelatedField(
        queryset=Class.objects.all())
    profile_thumbnail = HyperlinkedSorlImageField('128x128',
                                                  options={'crop': 'center'},
                                                  source='profile_photo',
                                                  read_only=True)

    class Meta:
        model = Child
        fields = (
            'id',
            'assigned_class',
            'name',
            'gender',
            'birthday',
            'address',
            'parent_relationship',
            'parent_phone_number',
            'profile_photo',
            'profile_thumbnail',
        )
        read_only_fields = ('id', )
Example #32
0
class BasePostSerializer(serializers.ModelSerializer):
    user = UserPostSerializer(many=False)
    image = HyperlinkedSorlImageField('1024', required=False)
    like_count = serializers.SerializerMethodField()
    is_like = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'title', 'description', 'video_file', 'image',
                  'image_width', 'image_height', 'views', 'like_count',
                  'is_like', 'comment_status', 'user')

    def get_like_count(self, obj):
        return obj.post_likes.all().count()

    def get_is_like(self, obj):
        request = self.context.get('request')
        user = request.user
        if user.is_authenticated:
            if obj.post_likes.filter(user=user).exists():
                return True
            else:
                return False
        return False
    def test_to_representation_attribute_error(self, mocked_to_representation):
        field = HyperlinkedSorlImageField("200")

        image = field.to_representation("URL IMAGE")
        self.assertEqual("ORIGINAL_URL", image)