Ejemplo n.º 1
0
class PetSerializer(ModelSerializer):
    owner = OwnerSerializer()
    city = CitySerializer()
    kind = StringRelatedField()

    status = CharField(source="status.description", read_only=True)
    sex = CharField(source="get_sex", read_only=True)
    size = CharField(source="get_size", read_only=True)
    thumb_picture = ImageField(read_only=True)

    id = HyperlinkedIdentityField(lookup_field="slug",
                                  lookup_url_kwarg="pk_or_slug",
                                  read_only=True,
                                  view_name="meupet:detail")

    class Meta:
        model = Pet
        fields = pet_fields
Ejemplo n.º 2
0
class ProductSerializer(ModelSerializer):
    is_on_sale = BooleanField(read_only=True)
    current_price = FloatField(read_only=True)
    description = CharField(min_length=2, max_length=200)
    cart_items = OrderSerializer(many=True, read_only=True)
    # price = FloatField(min_value=1.00, max_value=100000)
    price = DecimalField(
        min_value=1.00, max_value=100000,
        max_digits=None, decimal_places=2,
    )
    sale_start = DateTimeField(
        required=False,
        input_formats=['%I:%M %p %d %B %Y'], format=None, allow_null=True,
        help_text='Accepted format is "12:01 PM 16 April 2019"',
        style={'input_type': 'text', 'placeholder': '12:01 AM 28 July 2019'},
    )
    sale_end = DateTimeField(
        required=False,
        input_formats=['%I:%M %p %d %B %Y'], format=None, allow_null=True,
        help_text='Accepted format is "12:01 PM 16 April 2019"',
        style={'input_type': 'text', 'placeholder': '12:01 AM 28 July 2019'},
    )
    photo = ImageField(default=None)
    warranty = FileField(write_only=True, default=None)

    class Meta:
        model = Product
        fields = (
            'id', 'name', 'description', 'price', 'sale_start', 'sale_end',
            'is_on_sale', 'current_price', 'cart_items',
            'photo', 'warranty',
        )

    def update(self, instance, validated_data):
        if validated_data.get('warranty', None):
            instance.description += '\n\nWarranty Information:\n'
            instance.description += b'; '.join(
                validated_data['warranty'].readlines()
            ).decode('utf-8')
        return super().update(instance, validated_data)

    def create(self, validated_data):
        validated_data.pop('warranty')  # remove
        return Product.objects.create(**validated_data)
Ejemplo n.º 3
0
class PostSerializer(TaggitSerializer, serializers.ModelSerializer):
    photos = ListField(child=ImageField(), write_only=True)
    _photos = PhotoSerializer(many=True, read_only=True, source='photos')
    owner = SimpleProfileSerializer(read_only=True)
    tags = TagListSerializerField(required=False)

    class Meta:
        model = Post
        fields = ('id', 'content', 'owner', 'photos', '_photos', 'tags')
        read_only_fields = ('owner', )

    def create(self, validated_data):
        """Post를 만든 후 이미지들로 Photo들 생성"""
        photos = validated_data.pop('photos')
        post = Post.objects.create(**validated_data)
        photo_bulk_list = []
        for image_data in photos:
            photo = Photo(post=post, img=image_data)
            photo_bulk_list.append(photo)
        Photo.objects.bulk_create(photo_bulk_list)
        return post
Ejemplo n.º 4
0
class ImageUploadSerializer(Serializer):
    image = ImageField()

    def validate_image(self, value):
        self.form = MarkdownXImageForm(files={"image": value},
                                       user=self.context.get("request").user)
        if self.form.is_valid():
            return value
        raise ValidationError("Invalid image")

    def create(self, data):
        image_path = self.form.save(commit=True)
        image_url = "%s%s" % (settings.SOCIALHOME_URL, image_path)
        image_code = '![]({})'.format(image_url)
        return {
            "code": image_code,
            "url": image_url,
        }

    def to_representation(self, instance):
        return instance
class BlogSerailzer2(Serializer):
    blogText= CharField(error_messages={'required':'blogText key is required', 'blank':'blogText is required'})
    blogImg= ImageField(error_messages={'required':'blogImg key is required', 'blank':'blogImg is required'})
    createdBy= CharField(error_messages={'required':'createdBy key is required', 'blank':'createdBy is required'})
    message2 = CharField(read_only=True)

    def validate(self, data):
        blogText = data.get('blogText')

        if len(blogText) < 5:
            raise ValidationError('blogText length should be atleast 5')

        return data

    def create(self, validated_data):
        user=''
        try:
            user = User.objects.get(id=validated_data['createdBy'])
        except:
            pass
        blog = Blog(blogText=validated_data['blogText'], blogImg=validated_data.get('blogImg'), createdBy=user)
        blog.save()
        validated_data['message2'] = "my new message"
        return validated_data
Ejemplo n.º 6
0
class ImageUploadSerializer(serializers.ModelSerializer):
    upload = ImageField(source="image", required=True)
    url = serializers.SerializerMethodField()
    uploaded = serializers.SerializerMethodField()
    fileName = serializers.SerializerMethodField()

    def get_url(self, obj):
        file_obj = obj.image
        try:
            if not file_obj:
                return None
        except FileNotFoundError as e:
            logger.error("File does not exist on filesystem ", exc_info=e)
            return None
        return file_obj.url

    def get_uploaded(self, obj):
        file_obj = obj.image
        try:
            if not file_obj:
                return 0
        except FileNotFoundError as e:
            logger.error("File does not exist on filesystem ", exc_info=e)
            return 0
        return 1

    def get_fileName(self, obj):
        return obj.name

    def create(self, validated_data):
        validated_data["name"] = validated_data.get("image")._name
        return super().create(validated_data)

    class Meta:
        model = Image
        fields = ("pk", "upload", "url", "uploaded", "fileName")
Ejemplo n.º 7
0
class KeyFigureSerializer(serializers.ModelSerializer):
    image = ImageField(max_length=None, allow_empty_file=False, use_url=True)

    class Meta:
        model = KeyFigure
        exclude = ('article', )
Ejemplo n.º 8
0
     FileField(),
     {
         'type': 'string',
         'format': 'binary'
     },
 ),
 (
     # FloatField
     FloatField(),
     {
         'type': 'number'
     },
 ),
 (
     # ImageField
     ImageField(),
     {
         'type': 'string',
         'format': 'binary'
     },
 ),
 (
     # SlugField
     SlugField(),
     {
         'type': 'string',
         'pattern': '^[-a-zA-Z0-9_]+$'
     },
 ),
 (
     # TimeField
Ejemplo n.º 9
0
class UniversityLogoSerializer(serializers.ModelSerializer):
    image = ImageField(max_length=None, allow_empty_file=False)

    class Meta:
        model = UniversityLogo
        fields = ('id', 'image', 'name')
Ejemplo n.º 10
0
class ReportImageSerializer(ModelSerializer):
    filepond = ImageField(source="image")

    class Meta:
        model = ReportImage
        fields = "__all__"
Ejemplo n.º 11
0
class ImageUploaderSerializer(UploadeBaseSerializer):
    image = ListField(child=ImageField(), required=True)
Ejemplo n.º 12
0
class ImageCreateSerializer(ImageSerializer):
    image = ImageField(required=True)

    def create(self, validated_data):
        validated_data["name"] = validated_data.get("image")._name
        return super().create(validated_data)