Beispiel #1
0
class UniversityRetrieveSerializer(serializers.ModelSerializer):
    grade = serializers.ReadOnlyField(source='get_grade')
    professors_count = serializers.ReadOnlyField(source='count')
    departments = serializers.SerializerMethodField()
    extra_info = serializers.SerializerMethodField()
    emblem = serializers.ImageField(use_url=False)

    def get_departments(self, university):
        request = self.context.get('request', None)
        department_slug = request.GET.get('department')
        queryset = Department.objects.all()
        context = {'request': request, 'university': university}
        if department_slug:
            department = get_object_or_404(queryset, slug=department_slug)
            serializer = DepartmentRetrieveSerializer(instance=department,
                                                      context=context)
        else:
            serializer = DepartmentSerializer(instance=queryset,
                                              many=True,
                                              context=context)
        return serializer.data

    def get_extra_info(self, university):
        extra_info = {}
        request = self.context.get('request', None)
        context = {'request': request}
        professors = Professor.objects.filter(
            university=university, score__gt=0).select_related('university')
        comments = Comment.objects.filter(
            professor__in=professors).select_related('created_by').exclude(
                body__exact='').order_by('-created_at', '-id')[:5]
        hi_professors = professors.order_by('-score')[:5]
        low_professors = professors.order_by('score')[:5]
        extra_info = {
            'hi_professors':
            ProfessorListSerializer(instance=hi_professors,
                                    context=context,
                                    many=True).data,
            'low_professors':
            ProfessorListSerializer(instance=low_professors,
                                    context=context,
                                    many=True).data,
            'recent_comments':
            CommentSerializer(instance=comments, many=True).data
        }
        return extra_info

    class Meta:
        model = University
        fields = (
            'id',
            'name',
            'slug',
            'city',
            'emblem',
            'grade',
            'professors_count',
            'extra_info',
            'departments',
        )
        lookup_field = 'slug'
        extra_kwargs = {'url': {'lookup_field': 'slug'}}
class MovieSerializer(serializers.ModelSerializer):
	image = serializers.ImageField(max_length=None,use_url=True)
	class Meta:
		model = Moviedata
		fields = ['id','name','duration','rating','typ','image']
Beispiel #3
0
class PictureSerializer(serializers.ModelSerializer):
    thumbnail = serializers.ImageField(read_only=True)

    class Meta:
        model = Pictures
        fields = ['profile', 'thumbnail']
Beispiel #4
0
class UserProfileSerializer(PublicUserProfileSerializer):
    picture_upload = serializers.ImageField(use_url=True, write_only=True)

    class Meta(PublicUserProfileSerializer.Meta):
        fields = PublicUserProfileSerializer.Meta.fields + (
            'display_name', 'email', 'deleted', 'last_login', 'picture_upload',
            'last_login_ip', 'read_dev_agreement', 'is_verified',
        )
        writeable_fields = (
            'biography', 'display_name', 'homepage', 'location', 'occupation',
            'picture_upload', 'username',
        )
        read_only_fields = tuple(set(fields) - set(writeable_fields))

    def validate_biography(self, value):
        if has_links(clean_nl(unicode(value))):
            # There's some links, we don't want them.
            raise serializers.ValidationError(
                ugettext(u'No links are allowed.'))
        return value

    def validate_display_name(self, value):
        if DeniedName.blocked(value):
            raise serializers.ValidationError(
                ugettext(u'This display name cannot be used.'))
        return value

    def validate_username(self, value):
        # All-digits usernames are disallowed since they can be confused for
        # user IDs in URLs.
        if value.isdigit():
            raise serializers.ValidationError(
                ugettext(u'Usernames cannot contain only digits.'))

        slug_validator(
            value, lower=False,
            message=ugettext(u'Enter a valid username consisting of letters, '
                             u'numbers, underscores or hyphens.'))
        if DeniedName.blocked(value):
            raise serializers.ValidationError(
                ugettext(u'This username cannot be used.'))

        # Bug 858452. Remove this check when collation of the username
        # column is changed to case insensitive.
        if (UserProfile.objects.exclude(id=self.instance.id)
                       .filter(username__iexact=value).exists()):
            raise serializers.ValidationError(
                ugettext(u'This username is already in use.'))

        return value

    def validate_picture_upload(self, value):
        if value.content_type not in ('image/png', 'image/jpeg'):
            raise serializers.ValidationError(
                ugettext(u'Images must be either PNG or JPG.'))

        if value.size > settings.MAX_PHOTO_UPLOAD_SIZE:
            raise serializers.ValidationError(
                ugettext(u'Please use images smaller than %dMB.' %
                         (settings.MAX_PHOTO_UPLOAD_SIZE / 1024 / 1024 - 1)))
        return value

    def update(self, instance, validated_data):
        instance = super(UserProfileSerializer, self).update(
            instance, validated_data)

        photo = validated_data.get('picture_upload')
        if photo:
            tmp_destination = instance.picture_path + '__unconverted'

            with default_storage.open(tmp_destination, 'wb') as temp_file:
                for chunk in photo.chunks():
                    temp_file.write(chunk)
            instance.update(picture_type=photo.content_type)
            resize_photo.delay(tmp_destination, instance.picture_path,
                               set_modified_on=[instance])
        return instance
Beispiel #5
0
class CreatePostSerializer(serializers.ModelSerializer):
    filename = serializers.ListField(child=serializers.ImageField(
        allow_empty_file=False))

    class Meta:
        model = AccountPost
        fields = [
            'account', 'caption', 'recommendation_name', 'recommendation_type',
            'recommendation_phone_iso_code', 'recommendation_phone_dial_code',
            'recommendation_phone_number', 'url', 'url_action_text',
            'location_name', 'latitude', 'longitude', 'filename', 'post_type'
        ]

    def create(self, validated_data):
        account = self.validated_data['account']
        caption = self.validated_data['caption']
        recommendation_name = self.validated_data.get('recommendation_name',
                                                      None)
        recommendation_type = self.validated_data.get('recommendation_type',
                                                      None)
        recommendation_phone_iso_code = self.validated_data.get(
            'recommendation_phone_iso_code', None)
        recommendation_phone_dial_code = self.validated_data.get(
            'recommendation_phone_dial_code', None)
        recommendation_phone_number = self.validated_data.get(
            'recommendation_phone_number', None)
        post_type = self.validated_data.get('post_type', None)
        url = self.validated_data.get('url', None)
        url_action_text = self.validated_data.get('url_action_text', None)
        location_name = self.validated_data.get('location_name', None)
        latitude = self.validated_data.get('latitude', None)
        longitude = self.validated_data.get('longitude', None)
        filename = validated_data.pop('filename')

        # validate filename
        if len(filename) > 10:
            raise serializers.ValidationError(
                {'filename': ['exceeded the number of upload files']})

        # save post
        windowshoppi_post = AccountPost.objects.create(
            account=account,
            caption=caption,
            recommendation_name=recommendation_name,
            recommendation_type=recommendation_type,
            recommendation_phone_iso_code=recommendation_phone_iso_code,
            recommendation_phone_dial_code=recommendation_phone_dial_code,
            recommendation_phone_number=recommendation_phone_number,
            url=url,
            url_action_text=url_action_text,
            location_name=location_name,
            latitude=latitude,
            longitude=longitude,
            post_type=post_type)

        try:
            for image in filename:
                PostImage.objects.create(post=windowshoppi_post,
                                         filename=image)

            # check if url is saved
            if windowshoppi_post.url:
                # verify url
                verify_url(windowshoppi_post.id)

            return {'id': windowshoppi_post.id}
        except:
            # make uploaded post inactive if error happen on uploading image(s)
            windowshoppi_post.active = False
            windowshoppi_post.error_happened_on_uploading_image = True
            windowshoppi_post.save()
            return 'error_occurred'
Beispiel #6
0
class TempAppImagesSerializer(ModelSerializer):
    app_images = serializers.ImageField(max_length=None, use_url='app_images')

    class Meta:
        model = TempAppImgs
        fields = ['id', 'app', 'app_images']
Beispiel #7
0
class MiniSliderOfferEngravingSerializer(serializers.ModelSerializer):
    image_thumbnail = serializers.ImageField()
    class Meta:
        model = MiniSliderOfferEngraving
        fields = ('id','title', 'image', 'image_thumbnail')
Beispiel #8
0
class CommunityPostImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(read_only=True)

    class Meta:
        model = PostImage
        fields = ('image', 'width', 'height')
class ProfileSerializer(serializers.ModelSerializer):

    email = serializers.CharField(source='user.email', read_only=True)
    skills = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=Skill.objects.all())
    #skills = SkillSerializer(many = True,required= False, read_only=True)
    #values = ValueSerializer(many = True,required = False)
    #following = UserCompactSerializer(many=True, required = False, read_only = True)
    following_count = serializers.SerializerMethodField()
    followers = UserCompactSerializer(many = True, required=False)
    followers_count = serializers.SerializerMethodField()
    avatar = serializers.ImageField(source='user.avatar.avatar', read_only = True)
    me_following = serializers.SerializerMethodField()

    def get_following_count(self, profile):
        return profile.following.filter(profile__deactivated_at__isnull=True).count()

    def get_followers_count(self, profile):
        return User.objects.filter(profile__following__id__contains=profile.user.id).count()

    def get_me_following(self, profile):
        if(self.context.get('request').user.profile.following.filter(id=profile.id).exists()):
            return True
        else:
            return False

    """ def update(self, instance, validated_data):
        skills_data = []
        values_data = []
        askills_data = []
        print("@@@@@@@@@@@@@",validated_data.keys())
        if('skills' in validated_data.keys()):
            skills_data = validated_data.pop('skills')
            print("***************",skills_data)
        if('values' in validated_data.keys()):
            values_data = validated_data.pop('values')
            print("################",values_data)
        instance = super().update(instance, validated_data)
        if(len(skills_data)>0):
            instance.skills.set([])
            for skill_data in skills_data:
                nskills = Skill.objects.filter(id=skill_data.id)
                if(nskills.exists()):
                    nskill = nskills.first()
                    instance.skills.add(nskill)

        if(len(askills_data)>0):
            instance.askills.set([])
            for askill_data in askills_data:
                naskills = Skill.objects.filter(id=askill_data.id)
                if(naskills.exists()):
                    naskill = naskills.first()
                    instance.askills.add(naskill)

        if(len(values_data)>0):
            instance.values.set([])
            for value_data in values_data:
                nvalues = Value.objects.filter(id=value_data.id)
                if(nvalues.exists()):
                    nvalue = nvalues.first()
                    instance.values.add(nvalue)

        return instance """

    """ def update(self, instance, validated_data):
        skills = validated_data.pop('skills', [])
        instance = super().update(instance, validated_data)
        for skill_data in skills:
            skill = Skill.objects.get(title=skill_data.get('title'))
            instance.skills.add(skill)
        values = validated_data.pop('values', [])
        instance = super().update(instance, validated_data)
        for value_data in values:
            value = Value.objects.get(title=value_data.get('title'))
            instance.values.add(value)
        return instance  """

    class Meta:
        model = Profile
        fields = ['askills','me_following','id','firstname','lastname','email','gender','birthdate','bio','phone','city','languages','skills','values','q1','q2','q3','pic','highested','designation','tandcversion','avatar','completed_at','followers', 'following', 'followers_count', 'following_count','institution','state', 'company']
class UploadSerializer(serializers.Serializer):
    upload = serializers.ImageField(required=True)
Beispiel #11
0
class RegisterGuideSerializer(serializers.Serializer):
    name = serializers.CharField(allow_null=True)
    age = serializers.IntegerField(allow_null=True)
    language = serializers.CharField(allow_null=True)
    photo = serializers.ImageField(allow_null=True)
    about = serializers.CharField(allow_null=True)
    mail = serializers.EmailField(allow_null=True)
    phone = serializers.CharField()
    guide_format = serializers.CharField()

    def create(self, validated_data):
        this_password = str(random.randint(100000000, 999999999))
        user = User.objects.create_user(username=validated_data['phone'],
                                        email=validated_data['mail'],
                                        password=this_password)
        register_data = UserRegisterData.objects.create(
            user=user,
            code=str(random.randint(100000, 999999)),
            status='code',
            user_password=this_password)
        tourist_info = TouristInfo.objects.create(
            user=user,
            reminder=False,
            news=False,
            notifications=False,
            guide=True,
            name=validated_data['name'],
            photo=None,
            mail=validated_data['mail'],
            phone=validated_data['phone'],
            admin_status='new')
        guide_info = GuideInfo.objects.create(
            user=user,
            name=validated_data['name'],
            age=validated_data['age'],
            language=validated_data['language'],
            guide_format=validated_data['guide_format'],
            photo=validated_data['photo'],
            about=validated_data['about'],
            mail=validated_data['mail'],
            phone=validated_data['phone'],
            admin_status='new',
            reminder=False,
            news=False,
            notifications=False)

        photo = None
        try:
            photo = guide_info.photo.path
        except:
            photo = None

        print(photo)

        if photo != None:
            open_file = open(str(photo), "rb")
            django_open = File(open_file)

            #узнать формат фото
            photo_format = ''
            for i in range(1, len(photo)):
                if photo[len(photo) - i] == '.':
                    break
                else:
                    photo_format = photo[len(photo) - i] + photo_format

            tourist_info.photo.save('hz.' + photo_format,
                                    django_open,
                                    save=True)
            tourist_info.save()

        return register_data

    def update(self, instance, validated_data):
        instance.name = validated_data['name']
        instance.age = validated_data['age']
        instance.language = validated_data['language']
        instance.photo = validated_data['photo']
        instance.about = validated_data['about']
        instance.guide_format = validated_data['guide_format']

        instance.save()
        return instance
class ImagePostSerializer(serializers.Serializer):
    file = serializers.ImageField(max_length=None, allow_empty_file=False)
    tags = serializers.CharField(max_length=200,
                                 allow_blank=True,
                                 required=False)
Beispiel #13
0
class ImageUploadSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(use_url=True)

    class Meta:
        model = ImageUpload
        fields = ('url', 'pk', 'title', 'image')
Beispiel #14
0
class UserDetailsSerializer(serializers.ModelSerializer):
    posts = PostSerializer(many=True, read_only=True)
    email_status = serializers.SerializerMethodField()
    avatar_url = serializers.SerializerMethodField()
    profile = ProfileSerializer()
    avatar = serializers.ImageField(write_only=True, required=False)

    class Meta:
        model = UserModel
        fields = ('username', 'email', 'email_status', 'profile', 'avatar',
                  'avatar_url', 'posts')

    def get_email_status(self, obj):
        email_address = EmailAddress.objects.get(user=obj)
        return email_address.verified

    def get_avatar_url(self, obj, size=settings.AVATAR_DEFAULT_SIZE):
        for provider_path in settings.AVATAR_PROVIDERS:
            provider = import_string(provider_path)
            avatar_url = provider.get_avatar_url(obj, size)
            if avatar_url:
                return self.context['request'].build_absolute_uri(avatar_url)

    def validate_name(self, name):
        pattern = "^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ðء-ي]+[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ðء-ي]+[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ðء-ي]*$"
        compiler = re.compile(pattern)
        if not compiler.match(name):
            raise serializers.ValidationError(
                _("Make sure it contains only letters and spaces."))

        return name

    def validate_avatar(self, avatar):
        if settings.AVATAR_ALLOWED_FILE_EXTS:
            root, ext = os.path.splitext(avatar.name.lower())
            if ext not in settings.AVATAR_ALLOWED_FILE_EXTS:
                valid_exts = ", ".join(settings.AVATAR_ALLOWED_FILE_EXTS)
                error = _("%(ext)s is an invalid file extension. "
                          "Authorized extensions are : %(valid_exts_list)s")
                raise serializers.ValidationError(error % {
                    'ext': ext,
                    'valid_exts_list': valid_exts
                })

        if avatar.size > settings.AVATAR_MAX_SIZE:
            error = _("Your file is too big: %(size)s, "
                      "the maximum allowed size is: %(max_valid_size)s")

            raise serializers.ValidationError(
                error % {
                    'size': filesizeformat(avatar.size),
                    'max_valid_size': filesizeformat(settings.AVATAR_MAX_SIZE)
                })

    def validate_email(self, email):
        email = get_adapter().clean_email(email)
        if email and email_address_exists(
                email, exclude_user=self.context.get('request').user):
            raise serializers.ValidationError(
                _("A user is already registered with this e-mail address."))
        return email

    def update(self, instance, validated_data):
        request = self.context.get('request')

        profile = validated_data.get('profile', None)
        instance.username = validated_data.get('username', instance.username)
        instance.first_name = validated_data.get('first_name',
                                                 instance.first_name)

        if profile:
            bio = profile.get("bio")
            location = profile.get("location")
            birth_date = profile.get("birth_date")
            first_name = profile.get("first_name")
            last_name = profile.get("last_name")
            if bio and bio != instance.profile.bio:
                instance.profile.bio = bio
            if location and location != instance.profile.location:
                instance.profile.location = location
            if birth_date and birth_date != instance.profile.birth_date:
                instance.profile.birth_date = birth_date
            if first_name and first_name != instance.profile.first_name:
                instance.profile.first_name = first_name
            if last_name and last_name != instance.profile.last_name:
                instance.profile.last_name = last_name

        email = validated_data.get('email', None)
        if email and email != instance.email:
            adapter = get_adapter()
            adapter.send_mail('account/email/email_change', instance.email, {})
            email_address = EmailAddress.objects.get(user=instance,
                                                     verified=True)
            email_address.change(request, email, True)
            instance.email = email

        if 'avatar' in request.FILES:
            avatar = Avatar(user=instance, primary=True)
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar, user=instance, avatar=avatar)

        instance.save()

        # sync_sso(instance)

        return instance
Beispiel #15
0
class ProductSerializer(serializers.ModelSerializer):
    is_on_sale = serializers.BooleanField(read_only=True)
    current_price = serializers.FloatField(read_only=True)
    description = serializers.CharField(min_length=2, max_length=200)
    cart_items = serializers.SerializerMethodField()
    #price = serializers.FloatField(min_value=1.00, max_value=100000)
    price = serializers.DecimalField(
        min_value=1.00,
        max_value=100000,
        max_digits=None,
        decimal_places=2,
    )
    sale_start = serializers.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 = serializers.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 = serializers.ImageField(default=None)
    warranty = serializers.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 get_cart_items(self, instance):
        items = ShoppingCartItem.objects.filter(product=instance)
        return CartItemSerializer(items, many=True).data

    # def to_representation(self, instance):
    #     data = super().to_representation(instance)
    #     data['is_on_sale'] = instance.is_on_sale()
    #     data['current_price'] = instance.current_price()
    #     return data

    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()
        return super().update(instance, validated_data)

    def create(self, validated_data):
        validated_data.pop('warranty')
        return Product.objects.create(**validated_data)
Beispiel #16
0
class SignalCreateSerializer(serializers.ModelSerializer):
    location = _NestedLocationModelSerializer()
    reporter = _NestedReporterModelSerializer()
    status = _NestedStatusModelSerializer()
    category = _NestedCategoryModelSerializer(source='category_assignment')
    priority = _NestedPriorityModelSerializer(required=False, read_only=True)
    image = serializers.ImageField(source='image_crop', read_only=True)

    incident_date_start = serializers.DateTimeField()

    class Meta(object):
        model = Signal
        fields = (
            'id',
            'signal_id',
            'source',
            'image',
            'text',
            'text_extra',
            'status',
            'location',
            'category',
            'reporter',
            'priority',
            'created_at',
            'updated_at',
            'incident_date_start',
            'incident_date_end',
            'operational_date',
            'extra_properties',
        )
        read_only_fields = (
            'id',
            'signal_id',
            'created_at',
            'updated_at',
        )
        extra_kwargs = {
            'id': {
                'label': 'ID'
            },
            'signal_id': {
                'label': 'SIGNAL_ID'
            },

            # Because we want to disable V0 on short term we use the V1 validator for now
            'extra_properties': {
                'validators': [
                    ExtraPropertiesValidator(filename=os.path.join(
                        os.path.dirname(__file__), '..', 'v1', 'json_schema',
                        'extra_properties.json'))
                ]
            },  # noqa
        }

    def create(self, validated_data):
        status_data = validated_data.pop('status')
        location_data = validated_data.pop('location')
        reporter_data = validated_data.pop('reporter')
        category_assignment_data = validated_data.pop('category_assignment')

        image = validated_data.pop('image', None)

        signal = Signal.actions.create_initial(validated_data, location_data,
                                               status_data,
                                               category_assignment_data,
                                               reporter_data)

        if image:
            Signal.actions.add_image(image, signal)

        return signal

    def validate(self, data):
        image = self.initial_data.get('image', False)
        if image:
            if image.size > 8388608:  # 8MB = 8*1024*1024
                raise ValidationError("Maximum photo size is 8Mb.")

        if image:
            data['image'] = image

        return data
Beispiel #17
0
class CardImageSerializer(serializers.ModelSerializer):
    img_file = serializers.ImageField(use_url=True)

    class Meta:
        model = CardImage
        fields = ('id', 'info', 'img_url', 'img_file')
Beispiel #18
0
class AccountSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(write_only=True,
            validators=[validators.UniqueValidator(queryset=User.objects.all())])
    password = serializers.CharField(write_only=True, required=False)
    confirm_password = serializers.CharField(write_only=True, required=False)
    major = serializers.CharField(required=True)
    image = serializers.ImageField(default='Images/None/No-img.jpg', required=False)

    class Meta:
        model = User
        fields = ('id', 'email', 'username', 'major', 'bio', 'image', 'date_joined', 'updated_at',
                  'first_name', 'last_name', 'full_name', 'password',
                  'confirm_password',)
        read_only_fields = ('date_joined', 'updated_at', 'full_name')


    def validate(self, attrs):
        if 'password' in attrs:
            if attrs['password'] != attrs['confirm_password']:
                raise serializers.ValidationError("Password is not matched with a confirm password")
        return attrs

    def to_representation(self, obj):
        returnObj = super(AccountSerializer,self).to_representation(obj)
        followers_count = len(followers(obj))
        following_count = len(following(obj))
        total_posts = len(Post.objects.filter(author=obj.id))
        new_obj = {}

        # if isinstance(self.context['request'].user, User):
        if self.context['request'].user.id == obj.id:
            new_obj["email"] = obj.email
        new_obj.update({
            "following": following_count,
            "followers": followers_count,
            'total_posts': total_posts,
            "am_I_following": is_following(self.context['request'].user, obj)
        })
        returnObj.update(new_obj)
        return returnObj


    def update(self, instance, validated_data):
        # instance.email = validated_data.get('email', instance.email)
        # instance.username = validated_data.get('username', instance.username)
        instance.first_name = validated_data.get('first_name', instance.first_name)
        instance.last_name = validated_data.get('last_name', instance.last_name)
        instance.major = validated_data.get('major', instance.major)
        instance.bio = validated_data.get('bio', instance.bio)
        instance.image = validated_data.get('image', instance.image)

        instance.save()

        if self.checkPassword(validated_data):
            instance.set_password(validated_data.get('password'))
            instance.save()

        return instance


    def checkPassword(self, validated_data):
        password = validated_data.get('password', None)
        confirm_password = validated_data.get('confirm_password', None)

        if password and confirm_password and password == confirm_password:
            return True
        return False
Beispiel #19
0
class ProfileSerializer(serializers.ModelSerializer):
    picture = serializers.ImageField()

    class Meta:
        model = models.Profile
        fields = '__all__'
Beispiel #20
0
from rest_framework import serializers
from .models import Task
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token


class TaskSerializer(serializers.ModelSerializer):
<<<<<<< HEAD
    image = serializers.ImageField(
        max_length=None, use_url=True, default='images/none/none.jpg')
    doc = serializers.FileField(
        max_length=None, use_url=True, default='docs/none/none.txt')

=======
    image = serializers.ImageField(max_length=None, use_url=True, default='images/none/none.jpg')
    doc = serializers.FileField(max_length=None, use_url=True, default='docs/none/none.txt')
>>>>>>> 01f0b9a05d2c9013f894ed51652932ce36af0dda
    class Meta:
        model = Task
        fields = ('id', 'task_name', 'task_desc',
                  'completed', 'date_created', 'image', 'doc')


class UserSerializer(serializers.ModelSerializer):
    # password = serializers.CharField(write_only=True)

    # # override Create method
    # def create(self, validated_data):
    #     user = get_user_model().objects.create(
    #         username = validated_data['username']
Beispiel #21
0
class MiniSliderOfferIndividualSerializer(serializers.ModelSerializer):
    image_thumbnail = serializers.ImageField()
    class Meta:
        model = MiniSliderOfferIndividual
        fields = ('id','title', 'image', 'image_thumbnail')
Beispiel #22
0
class ImgSerializer(serializers.ModelSerializer):
    img = serializers.ImageField(max_length=None, use_url=True)

    class Meta:
        model= Image
        fields= '__all__'
Beispiel #23
0
class PostSerializer(serializers.Serializer):
    #this is serializer for post and use Serializer
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=250)
    slug = serializers.SlugField(read_only=True, required=False)
    text = serializers.CharField(required=False)
    created_date = serializers.DateTimeField(read_only=True)
    update_date = serializers.DateTimeField(read_only=True)
    published_date = serializers.DateTimeField(required=False)
    draft = serializers.BooleanField(required=False)
    image_title = serializers.ImageField(read_only=True)
    #read_only is somting like we did not give that
    #in model need have default for this or null=True
    category = serializers.PrimaryKeyRelatedField(
        queryset=Category.objects.all(), required=False)
    #category and author for relations need defin another way

    #    allow_discussion = serializers.BooleanField()
    #we can use PostSetting hear

    #    author = UserSerializer(read_only=True)
    #get full data of auther instead of just author_id
    author = serializers.PrimaryKeyRelatedField(
        queryset=User.objects.all(),
        required=False)  #hear we just get author_id

    def validate_slug(self, slug):
        #slug can be all objects in uper
        try:
            q = Post.objects.get(slug=slug)
            raise serializers.ValidationError('slug must be uniqe')
        except Post.DoesNotExist:
            return slug

    def create(self, validated_data):
        #in form we do this:
        #form = PostForm(request.POST)
        #if form.is_valid:
        #   title = form.cleaned_data['title']
        #   ....
        #   ....
        #   post = Post.objects.create(title=form.cleaned_data['title'], slug=form.cleaned_data['slug'],.....)
        #   return render('base/post_detail.html', {post:post})
        #hear we can do esear
        return Post.objects.create(**validated_data)
        #**validated_data is a func that get object PostSerializer one by one
        #  like (title=validated_data['title'], slug=validated_data['slug'], ....).
        # "**" is python metod for get the all feild on top.


#        PostSetting.objects.create(
#            post=post,
#            allow_discussion=validated_data['allow_discussion']
#            )#chang PostSertting

    def update(self, instance, validated_data):
        #for update the data
        #instanse that the object we want update
        #validated_data is uper object
        instance.title = validated_data.get('title', instance.title)
        #means if exist get it [the first purameter in prantesis] or not put the default[the second parameter in pratisis]
        #        instance.slug = validated_data.get('slug', instance.slug)
        #        instance.text = validated_data.get('text', instance.text)
        #        instance.created_date = validated_data.get('created_date', instance.created_date)
        instance.published_date = validated_data.get('published_date',
                                                     instance.published_date)
        instance.draft = validated_data.get('draft', instance.draft)
        #        instance.image_title = validated_data.get('image_title', instance.image_title)
        instance.save()  #for save the uper fields
        return instance  #return the instance
Beispiel #24
0
class UserCreateSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(
        required=True,
        error_messages={'required': _('Campo Obrigatório')},
        validators=[
            validators.UniqueValidator(queryset=UserModel.objects.all())
        ])
    name = serializers.CharField(
        required=True, error_messages={'required': _('Campo Obrigatório')})
    cpf = serializers.CharField(
        required=False,
        validators=[
            BRCPFValidator(),
            validators.UniqueValidator(queryset=UserModel.objects.all())
        ])
    emailConfirm = serializers.BooleanField(source='email_confirm',
                                            default=False)
    shareEmail = serializers.BooleanField(source='share_email',
                                          required=False,
                                          default=False)
    sharePhone = serializers.BooleanField(source='share_phone',
                                          required=False,
                                          default=False)
    phoneNumber = serializers.CharField(
        source='phone_number',
        required=True,
        error_messages={'required': _('Campo Obrigatório')})
    password1 = serializers.CharField(
        source='password',
        label=_("Password"),
        write_only=True,
        error_messages={'required': _('Campo Obrigatório')},
        style={'input_type': 'password'},
        trim_whitespace=False)
    typeUser = serializers.ChoiceField(
        source='type_user',
        required=True,
        error_messages={'required': _('Campo Obrigatório')},
        choices=UserModel.TYPE_USER_CHOICES)
    uf = serializers.CharField(
        max_length=100,
        required=True,
        error_messages={'required': _('Campo Obrigatório')})
    city = serializers.CharField(
        max_length=150,
        required=True,
        error_messages={'required': _('Campo Obrigatório')})
    image = serializers.ImageField(required=False)

    class Meta:
        model = UserModel
        fields = ('email', 'name', 'cpf', 'emailConfirm', 'shareEmail',
                  'sharePhone', 'phoneNumber', 'password1', 'typeUser', 'uf',
                  'city', 'image')

    def create(self, validated_data):
        password = validated_data.pop('password')
        user = UserModel.objects.create(**validated_data)
        user.set_password(password)
        user.verify_email()
        if user.type_user == UserModel.RECEIVER:
            user.is_active = False
        user.save()
        return user

    def update(self, instance, validated_data):
        if 'password' in validated_data:
            password = validated_data.pop('password')
            user = super(UserCreateSerializer,
                         self).update(instance, validated_data)
            user.set_password(password)
            return user
        else:
            return super(UserCreateSerializer,
                         self).update(instance, validated_data)

    def validate_phoneNumber(self, value):
        number = re.sub(r'\D', '', value)
        if len(number) > 11 or len(number) < 10:
            raise exceptions.ValidationError(_('Número Inválido'))
        return number
Beispiel #25
0
class QuestionsSerializer(serializers.HyperlinkedModelSerializer):
    Image = serializers.ImageField(use_url=True)

    class Meta:
        model = Questions
        fields = ['url', 'id', 'Text', 'Image', 'Tags']
Beispiel #26
0
    def _make_badge_progress_response(self, course_key,
                                      block_event_badge_config,
                                      block_event_assertion):
        """

        """
        return {
            "course_id":
            CourseKeyField(source='course_key').to_representation(course_key),
            "block_id":
            UsageKeyField(source='usage_key').to_representation(
                block_event_badge_config.usage_key),
            "block_display_name":
            self.course_section_mapping.get(
                UsageKeyField(source='usage_key').to_representation(
                    block_event_badge_config.usage_key),
                '').get('display_name', ''),
            "block_order":
            self.course_section_mapping.get(
                UsageKeyField(source='usage_key').to_representation(
                    block_event_badge_config.usage_key),
                '').get('block_order', ''),
            "event_type":
            block_event_badge_config.event_type,
            "badge_class": {
                "slug":
                block_event_badge_config.badge_class.slug,
                "issuing_component":
                block_event_badge_config.badge_class.issuing_component,
                "display_name":
                block_event_badge_config.badge_class.display_name,
                "course_id":
                CourseKeyField(source='course_key').to_representation(
                    block_event_badge_config.badge_class.course_id),
                "description":
                block_event_badge_config.badge_class.description,
                "criteria":
                block_event_badge_config.badge_class.criteria,
                "image":
                branding_api.get_base_url(self.request.is_secure()) +
                serializers.ImageField(source='image').to_representation(
                    block_event_badge_config.badge_class.image),
            },
            "assertion": {
                "issuedOn": (block_event_assertion.data.get('issuedOn', '') if
                             hasattr(block_event_assertion, 'data') else ""),
                "expires": (block_event_assertion.data.get('expires', '')
                            if hasattr(block_event_assertion, 'data') else ""),
                "revoked":
                (block_event_assertion.data.get('revoked', False) if hasattr(
                    block_event_assertion, 'data') else False),
                "image_url": (block_event_assertion.image_url
                              if block_event_assertion else ""),
                "assertion_url": (block_event_assertion.assertion_url
                                  if block_event_assertion else ""),
                "entityId": (block_event_assertion.data.get('entityId', '') if
                             hasattr(block_event_assertion, 'data') else ""),
                "recipient": {
                    "plaintextIdentity": (block_event_assertion.user.email
                                          if block_event_assertion else ""),
                },
                "issuer": (block_event_assertion.assertion_issuer()
                           if block_event_assertion else {
                               "entityType": "",
                               "entityId": "",
                               "openBadgeId": "",
                               "name": "",
                               "image": "",
                               "email": "",
                               "description": "",
                               "url": "",
                           }),
            },
        }
Beispiel #27
0
class EarnerBadgeSerializer(serializers.Serializer):
    recipient_id = serializers.CharField(required=False)
    id = serializers.IntegerField(required=False)

    assertion = serializers.DictField(required=False, write_only=True)
    url = serializers.URLField(required=False, write_only=True)
    image = serializers.ImageField(required=False, write_only=True)

    json = V1InstanceSerializer(read_only=True)
    errors = serializers.ListField(read_only=True)

    def to_representation(self, obj):
        if self.context.get('format', 'v1') == 'plain':
            self.fields.json = serializers.DictField(read_only=True)
        return super(EarnerBadgeSerializer, self).to_representation(obj)

    def validate(self, data):
        # Remove empty DictField
        if data.get('assertion') == {}:
            data.pop('assertion', None)

        instance_input_fields = set(('url', 'image', 'assertion'))
        valid_inputs = {
            key: data.get(key)
            for key in instance_input_fields.intersection(data.keys())
        }

        if len(valid_inputs.keys()) != 1:
            raise serializers.ValidationError(
                "Only one instance input field allowed. Recieved " +
                json.dumps(valid_inputs.keys()))

        return data

    def create(self, validated_data):
        user = self.context.get('request').user
        image = None

        if validated_data.get('url') is not None:
            url = validated_data.get('url')
        elif validated_data.get('image') is not None:
            image = validated_data.get('image')
            image.open()
            url = get_instance_url_from_image(image)
        elif validated_data.get('assertion') is not None:
            url = get_instance_url_from_assertion(
                validated_data.get('assertion'))

        try:
            rbi = RemoteBadgeInstance(url)
        except DjangoValidationError as e:
            raise e

        abi = AnalyzedBadgeInstance(
            rbi,
            recipient_ids=[id.email for id in user.emailaddress_set.all()])
        if len(
            [x for x in abi.non_component_errors if x[0] == 'error.recipient'
             ]) != 0:
            raise serializers.ValidationError(RECIPIENT_ERROR)

        if not abi.is_valid():
            raise serializers.ValidationError(abi.all_errors())
        else:
            instance_kwargs = {'recipient_user': user}
            if image is not None:
                instance_kwargs['image'] = image

            new_instance = StoredBadgeInstance.from_analyzed_instance(
                abi, **instance_kwargs)

            return new_instance
Beispiel #28
0
class ProductSerializer(serializers.HyperlinkedModelSerializer):
    image = serializers.ImageField(max_length=None, allow_empty_file=False, allow_null=True, required=False)
    class Meta:
        model = Product
        fields = ('id', 'name', 'description', 'price', 'image', 'category')
Beispiel #29
0
class ProductSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    image = serializers.ImageField()
    price = serializers.DecimalField(max_digits=10, decimal_places=3)
    properties = serializers.JSONField()
    category = ProductCategorySerializer()
Beispiel #30
0
class ImageSerializer(serializers.Serializer):
    validate_image = FileValidator(max_size=1024 * 100)
    image = serializers.ImageField(validators=[validate_image])