예제 #1
0
class ClientSerializer(HyperlinkedModelSerializer):
	url = HyperlinkedIdentityField(view_name='iSupermarket:client-detail')
	user = CharField(read_only=True)
	class Meta:
		model = Client
		fields = ('url', 'name','lastName','phone','registration_date','country','city','user')
예제 #2
0
from rest_framework.fields import DateTimeField
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.serializers import ModelSerializer

from calendars.models import Event, Calendar

events_url = HyperlinkedIdentityField(
    view_name='api-calendars:events',
    lookup_field='id',
)


class CalendarListSerializer(ModelSerializer):
    url = events_url

    class Meta:
        model = Calendar
        fields = [
            "url",
        ]

    def get_events(self, obj):
        c_qs = Event.objects.filter(calendar=obj)
        events = EventListSerializer(c_qs, many=True).data

        return events


class EventListSerializer(ModelSerializer):
    class Meta:
        model = Event
예제 #3
0
class BasePricingStructureSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name="pricingstructure-detail", lookup_field='code')
    
    class Meta:
        model = contracts.PricingStructure
        fields = ['code', 'name']
예제 #4
0
class BasePlaceOfPerformanceSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name="placeofperformance-detail", lookup_field='id')
    
    class Meta:
        model = contracts.PlaceOfPerformance
        fields = ['id', 'country_code', 'country_name', 'state', 'zipcode']
예제 #5
0
from rest_framework.fields import SerializerMethodField
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.serializers import ModelSerializer

from account.api.serializers import UserDetailSerializer
from posts.models import Post

post_detail_url = HyperlinkedIdentityField(view_name='posts-api:detail',
                                           lookup_field='slug')


class PostDetailSerializer(ModelSerializer):
    url = post_detail_url
    user = UserDetailSerializer(read_only=True)
    image = SerializerMethodField()
    html = SerializerMethodField()
    comments = SerializerMethodField()

    class Meta:
        model = Post
        fields = [
            'url',
            'id',
            'user',
            'title',
            'slug',
            'content',
            'html',
            'publish',
            'image',
            'comments',
예제 #6
0
class BaseSetasideSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name="setaside-detail", lookup_field='code')
    
    class Meta:
        model = categories.SetAside
        fields = ['code', 'name', 'description', 'far_order']
예제 #7
0
class CommentChildSerializer(ModelSerializer):
    user = UserDetailSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = [
            'user',
            'id',
            'content',
            'timestamp',
        ]


comment_delete_url = HyperlinkedIdentityField(
    view_name='comment_api:comment_delete',
    lookup_field='id'
)
comment_update_url = HyperlinkedIdentityField(
    view_name='comment_api:comment_update',
    lookup_field='id'
)

comment_detail_url = HyperlinkedIdentityField(
    view_name='comment_api:comment_detail',
    lookup_field='id'
)


# this is the list serializer for the comment
class CommentSerializer(ModelSerializer):
    user = UserDetailSerializer(read_only=True)
예제 #8
0
    class TrekListSerializer(DynamicFieldsMixin, serializers.ModelSerializer):
        url = HyperlinkedIdentityField(view_name='apiv2:trek-detail')
        published = serializers.SerializerMethodField(read_only=True)
        geometry = geo_serializers.GeometryField(read_only=True,
                                                 source="geom2d_transformed",
                                                 precision=7)
        length_2d = serializers.SerializerMethodField(read_only=True)
        length_3d = serializers.SerializerMethodField(read_only=True)
        name = serializers.SerializerMethodField(read_only=True)
        description = serializers.SerializerMethodField(read_only=True)
        description_teaser = serializers.SerializerMethodField(read_only=True)
        difficulty = TrekDifficultySerializer(read_only=True)
        departure = serializers.SerializerMethodField(read_only=True)
        arrival = serializers.SerializerMethodField(read_only=True)
        themes = TrekThemeSerializer(many=True, read_only=True)
        networks = TrekNetworkSerializer(many=True, read_only=True)
        practice = TrekPracticeInTrekSerializer(read_only=True)
        external_id = serializers.CharField(source='eid')
        second_external_id = serializers.CharField(source='eid2')
        create_datetime = serializers.SerializerMethodField(read_only=True)
        update_datetime = serializers.SerializerMethodField(read_only=True)
        thumbnail = serializers.SerializerMethodField(read_only=True,
                                                      source='pictures')

        def get_update_datetime(self, obj):
            return obj.topo_object.date_update

        def get_create_datetime(self, obj):
            return obj.topo_object.date_insert

        def get_published(self, obj):
            return get_translation_or_dict('published', self, obj)

        def get_name(self, obj):
            return get_translation_or_dict('name', self, obj)

        def get_description(self, obj):
            return get_translation_or_dict('description', self, obj)

        def get_departure(self, obj):
            return get_translation_or_dict('departure', self, obj)

        def get_arrival(self, obj):
            return get_translation_or_dict('arrival', self, obj)

        def get_description_teaser(self, obj):
            return get_translation_or_dict('description_teaser', self, obj)

        def get_length_2d(self, obj):
            return round(obj.length_2d_m, 1)

        def get_length_3d(self, obj):
            return round(obj.length_3d_m, 1)

        def get_thumbnail(self, obj):
            for picture in obj.pictures:
                return {
                    'author': picture.author,
                    'title': picture.title,
                    'legend': picture.legend,
                    'url': build_url(self, picture.attachment_file.url),
                }
            return {}

        class Meta:
            model = trekking_models.Trek
            fields = ('id', 'url', 'name', 'description_teaser', 'description',
                      'departure', 'arrival', 'duration', 'difficulty',
                      'length_2d', 'length_3d', 'ascent', 'descent',
                      'min_elevation', 'max_elevation', 'themes', 'thumbnail',
                      'networks', 'practice', 'external_id',
                      'second_external_id', 'published', 'geometry',
                      'update_datetime', 'create_datetime')
예제 #9
0
    class TouristicContentSerializer(DynamicFieldsMixin,
                                     serializers.ModelSerializer):
        url = HyperlinkedIdentityField(
            view_name='apiv2:touristiccontent-detail')
        geometry = geo_serializers.GeometryField(read_only=True,
                                                 source="geom_transformed",
                                                 precision=7)
        create_datetime = serializers.DateTimeField(source='date_update')
        update_datetime = serializers.DateTimeField(source='date_insert')
        external_id = serializers.CharField(source='eid')
        types = serializers.SerializerMethodField(read_only=True)
        cities = serializers.SerializerMethodField(read_only=True)
        attachments = AttachmentSerializer(many=True)
        name = serializers.SerializerMethodField(read_only=True)
        description = serializers.SerializerMethodField(read_only=True)
        description_teaser = serializers.SerializerMethodField(read_only=True)
        practical_info = serializers.SerializerMethodField(read_only=True)
        pdf = serializers.SerializerMethodField('get_pdf_url')

        class Meta:
            model = tourism_models.TouristicContent
            fields = (
                'id',
                'attachments',
                'approved',
                'category',
                'description',
                'description_teaser',
                'geometry',
                'practical_info',
                'url',
                'cities',
                'create_datetime',
                'external_id',
                'name',
                'pdf',
                'portal',
                'published',
                'source',
                'structure',
                'themes',
                'update_datetime',
                'types',
                'contact',
                'email',
                'website',
                'reservation_system',
                'reservation_id',
            )

        def get_name(self, obj):
            return get_translation_or_dict('name', self, obj)

        def get_description(self, obj):
            return get_translation_or_dict('description', self, obj)

        def get_description_teaser(self, obj):
            return get_translation_or_dict('description_teaser', self, obj)

        def get_practical_info(self, obj):
            return get_translation_or_dict('practical_info', self, obj)

        def get_types(self, obj):
            return {
                obj.category.id * 100 + i:
                [t.id for t in getattr(obj, 'type{}'.format(i)).all()]
                for i in (1, 2)
            }

        def get_cities(self, obj):
            return [city.code for city in obj.published_cities]

        def _get_pdf_url_lang(self, obj, lang):
            if settings.ONLY_EXTERNAL_PUBLIC_PDF:
                file_type = get_object_or_404(common_models.FileType,
                                              type="Topoguide")
                if not common_models.Attachment.objects.attachments_for_object_only_type(
                        obj, file_type).exists():
                    return None
            urlname = 'tourism:touristiccontent_{}printable'.format(
                'booklet_' if settings.USE_BOOKLET_PDF else '')
            url = reverse(urlname,
                          kwargs={
                              'lang': lang,
                              'pk': obj.pk,
                              'slug': obj.slug
                          })
            request = self.context.get('request')
            if request:
                url = request.build_absolute_uri(url)
            return url

        def get_pdf_url(self, obj):
            lang = self.context.get('request').GET.get(
                'language', 'all') if self.context.get('request') else 'all'
            if lang != 'all':
                data = self._get_pdf_url_lang(obj, lang)
            else:
                data = {}
                for language in settings.MODELTRANSLATION_LANGUAGES:
                    data[language] = self._get_pdf_url_lang(obj, language)
            return data
예제 #10
0
    class TrekSerializer(DynamicFieldsMixin, serializers.ModelSerializer):
        url = HyperlinkedIdentityField(view_name='apiv2:trek-detail')
        published = serializers.SerializerMethodField(read_only=True)
        geometry = geo_serializers.GeometryField(read_only=True,
                                                 source="geom3d_transformed",
                                                 precision=7)
        length_2d = serializers.SerializerMethodField(read_only=True)
        length_3d = serializers.SerializerMethodField(read_only=True)
        name = serializers.SerializerMethodField(read_only=True)
        access = serializers.SerializerMethodField(read_only=True)
        ambiance = serializers.SerializerMethodField(read_only=True)
        description = serializers.SerializerMethodField(read_only=True)
        description_teaser = serializers.SerializerMethodField(read_only=True)
        departure = serializers.SerializerMethodField(read_only=True)
        disabled_infrastructure = serializers.SerializerMethodField(
            read_only=True)
        departure_geom = serializers.SerializerMethodField(read_only=True)
        arrival = serializers.SerializerMethodField(read_only=True)
        external_id = serializers.CharField(source='eid')
        second_external_id = serializers.CharField(source='eid2')
        create_datetime = serializers.SerializerMethodField(read_only=True)
        update_datetime = serializers.SerializerMethodField(read_only=True)
        attachments = AttachmentSerializer(many=True)
        gpx = serializers.SerializerMethodField('get_gpx_url')
        kml = serializers.SerializerMethodField('get_kml_url')
        pdf = serializers.SerializerMethodField('get_pdf_url')
        advice = serializers.SerializerMethodField(read_only=True)
        advised_parking = serializers.SerializerMethodField(read_only=True)
        parking_location = serializers.SerializerMethodField(read_only=True)
        children = serializers.ReadOnlyField(source='children_id')
        parents = serializers.ReadOnlyField(source='parents_id')
        public_transport = serializers.SerializerMethodField(read_only=True)
        elevation_area_url = serializers.SerializerMethodField()
        elevation_svg_url = serializers.SerializerMethodField()
        altimetric_profile = serializers.SerializerMethodField(
            'get_altimetric_profile_url')
        points_reference = serializers.SerializerMethodField(read_only=True)
        previous = serializers.ReadOnlyField(source='previous_id')
        next = serializers.ReadOnlyField(source='next_id')
        cities = serializers.SerializerMethodField(read_only=True)

        def get_update_datetime(self, obj):
            return obj.topo_object.date_update

        def get_create_datetime(self, obj):
            return obj.topo_object.date_insert

        def get_published(self, obj):
            return get_translation_or_dict('published', self, obj)

        def get_name(self, obj):
            return get_translation_or_dict('name', self, obj)

        def get_description(self, obj):
            return get_translation_or_dict('description', self, obj)

        def get_access(self, obj):
            return get_translation_or_dict('access', self, obj)

        def get_ambiance(self, obj):
            return get_translation_or_dict('ambiance', self, obj)

        def get_disabled_infrastructure(self, obj):
            return get_translation_or_dict('disabled_infrastructure', self,
                                           obj)

        def get_departure(self, obj):
            return get_translation_or_dict('departure', self, obj)

        def get_departure_geom(self, obj):
            geom = obj.geom3d_transformed
            if isinstance(geom, MultiLineString):
                geom = geom[0]
            return geom[0][:2]

        def get_arrival(self, obj):
            return get_translation_or_dict('arrival', self, obj)

        def get_description_teaser(self, obj):
            return get_translation_or_dict('description_teaser', self, obj)

        def get_length_2d(self, obj):
            return round(obj.length_2d_m, 1)

        def get_length_3d(self, obj):
            return round(obj.length_3d_m, 1)

        def get_gpx_url(self, obj):
            return build_url(
                self,
                reverse('trekking:trek_gpx_detail',
                        kwargs={
                            'lang': get_language(),
                            'pk': obj.pk,
                            'slug': obj.slug
                        }))

        def get_kml_url(self, obj):
            return build_url(
                self,
                reverse('trekking:trek_kml_detail',
                        kwargs={
                            'lang': get_language(),
                            'pk': obj.pk,
                            'slug': obj.slug
                        }))

        def _get_pdf_url_lang(self, obj, lang):
            if settings.ONLY_EXTERNAL_PUBLIC_PDF:
                file_type = get_object_or_404(common_models.FileType,
                                              type="Topoguide")
                if not common_models.Attachment.objects.attachments_for_object_only_type(
                        obj, file_type).exists():
                    return None
            urlname = 'trekking:trek_{}printable'.format(
                'booklet_' if settings.USE_BOOKLET_PDF else '')
            url = reverse(urlname,
                          kwargs={
                              'lang': lang,
                              'pk': obj.pk,
                              'slug': obj.slug
                          })
            request = self.context.get('request')
            if request:
                url = request.build_absolute_uri(url)
            return url

        def get_pdf_url(self, obj):
            lang = self.context.get('request').GET.get(
                'language', 'all') if self.context.get('request') else 'all'
            if lang != 'all':
                data = self._get_pdf_url_lang(obj, lang)
            else:
                data = {}
                for language in settings.MODELTRANSLATION_LANGUAGES:
                    data[language] = self._get_pdf_url_lang(obj, language)
            return data

        def get_advice(self, obj):
            return get_translation_or_dict('advice', self, obj)

        def get_advised_parking(self, obj):
            return get_translation_or_dict('advised_parking', self, obj)

        def get_parking_location(self, obj):
            if not obj.parking_location:
                return None
            point = obj.parking_location.transform(settings.API_SRID,
                                                   clone=True)
            return [round(point.x, 7), round(point.y, 7)]

        def get_public_transport(self, obj):
            return get_translation_or_dict('public_transport', self, obj)

        def get_elevation_area_url(self, obj):
            return build_url(
                self,
                reverse('trekking:trek_elevation_area',
                        kwargs={
                            'lang': get_language(),
                            'pk': obj.pk
                        }))

        def get_elevation_svg_url(self, obj):
            return build_url(
                self,
                reverse('trekking:trek_profile_svg',
                        kwargs={
                            'lang': get_language(),
                            'pk': obj.pk
                        }))

        def get_altimetric_profile_url(self, obj):
            return build_url(
                self,
                reverse('trekking:trek_profile',
                        kwargs={
                            'lang': get_language(),
                            'pk': obj.pk
                        }))

        def get_points_reference(self, obj):
            if not obj.points_reference:
                return None
            geojson = obj.points_reference.transform(settings.API_SRID,
                                                     clone=True).geojson
            return json.loads(geojson)

        def get_cities(self, obj):
            return [city.code for city in obj.published_cities]

        class Meta:
            model = trekking_models.Trek
            fields = ('id', 'access', 'accessibilities', 'advice',
                      'advised_parking', 'altimetric_profile', 'ambiance',
                      'arrival', 'ascent', 'attachments', 'children', 'cities',
                      'create_datetime', 'departure', 'departure_geom',
                      'descent', 'description', 'description_teaser',
                      'difficulty', 'disabled_infrastructure', 'duration',
                      'elevation_area_url', 'elevation_svg_url', 'external_id',
                      'geometry', 'gpx', 'information_desks', 'kml', 'labels',
                      'length_2d', 'length_3d', 'max_elevation',
                      'min_elevation', 'name', 'networks', 'next', 'parents',
                      'parking_location', 'pdf', 'points_reference', 'portal',
                      'practice', 'previous', 'public_transport', 'published',
                      'reservation_system', 'route', 'second_external_id',
                      'source', 'structure', 'themes', 'update_datetime',
                      'url')
예제 #11
0
class BasePoolSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name="pool-detail", lookup_field='id')

    class Meta:
        model = categories.Pool
        fields = ['id', 'name', 'number', 'vehicle', 'threshold']
예제 #12
0
class BasePscSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name="psc-detail", lookup_field='code')

    class Meta:
        model = categories.PSC
        fields = ['code', 'description']
예제 #13
0
class BookingsListSerializer(serializers.ModelSerializer):
    url = HyperlinkedIdentityField(view_name='bookings-detail')

    class Meta:
        model = Bookings
        fields = ('book_ref', 'book_date', 'total_amount', 'url')
예제 #14
0
    def _validate_resource_assignments(self, resource_assignment_dict,
                                       serializer):
        """
        Validates the resource assignments

        May throw ValidationError.
        Returns a validated dictionary.
        """
        if not isinstance(resource_assignment_dict, dict):
            raise ValidationError(["This field must be a JSON object"])

        unsatisfied_ips = set(
            InputPort.objects.filter(
                workflow_job__in=serializer.validated_data["workflow"].
                workflow_jobs.all(),
                connections__isnull=True,
            ))
        validated_resource_assignment_dict = {}

        # Keep track of the collection with multiple Resources or ResourceLists
        resource_collection_length = None
        resource_collection_ip = None

        for input_port, resources in resource_assignment_dict.items():
            # 1. InputPort is not satisfied
            h_ip = HyperlinkedIdentityField(view_name="inputport-detail")
            h_ip.queryset = InputPort.objects.all()
            try:
                ip = h_ip.to_internal_value(input_port)
            except ValidationError as e:
                e.detail = {input_port: e.detail}
                raise e

            if ip not in unsatisfied_ips:
                raise ValidationError(
                    {input_port: ["Assigned InputPort must be unsatisfied"]})
            unsatisfied_ips.remove(ip)
            types_of_ip = ip.input_port_type.resource_types.all()

            # 2. Resources and ResourceLists:
            if not isinstance(resources, list):
                raise ValidationError({
                    input_port:
                    ["A list of resources or resource lists is expected"]
                })

            h_res = HyperlinkedIdentityField(view_name="resource-detail")
            h_res.queryset = Resource.objects.all()
            h_resl = HyperlinkedIdentityField(view_name="resourcelist-detail")
            h_resl.queryset = ResourceList.objects.all()
            ress = []

            for index, r in enumerate(resources):
                try:
                    ress.append(h_res.to_internal_value(r))  # a Resource
                except ValidationError as e:
                    try:
                        ress.append(
                            h_resl.to_internal_value(r))  # a ResourceList
                    except ValidationError as e:
                        e.detail = {input_port: {index: e.detail}}
                        raise e

            # No empty collection
            if len(ress) == 0:
                raise ValidationError({
                    input_port:
                    ["It is not allowed to assign an empty collection"]
                })

            # Collection with multiple Resources or ResourceLists
            if len(ress) > 1:
                if resource_collection_length is None:
                    # This is the first resource collection we've encountered that has multiple items
                    resource_collection_length = len(ress)
                    resource_collection_ip = input_port
                else:
                    # Validate if the lengths are even
                    if len(ress) != resource_collection_length:
                        raise ValidationError({
                            input_port: [
                                "The number of assigned Resources of ResourceLists is not even with that of {}"
                                .format(resource_collection_ip)
                            ]
                        })

            ## Resource must be in project and resource types are matched
            ## If a ResourceList, it should not be empty and all individuals should satisfy the above requirements.
            for index, res in enumerate(ress):
                if isinstance(res, Resource):
                    if ip.input_port_type.is_list is True:
                        raise ValidationError({
                            input_port: {
                                index: [
                                    "The InputPort requires ResourceLists but is provided with Resources"
                                ]
                            }
                        })
                    if not res.resource_file:
                        raise ValidationError({
                            input_port: {
                                index: ["The resource file is not ready"]
                            }
                        })

                else:  # ResourceList
                    if ip.input_port_type.is_list is False:
                        raise ValidationError({
                            input_port: {
                                index: [
                                    "The InputPort requires Resources but is provided with ResourceLists"
                                ]
                            }
                        })

                    for i, r in enumerate(res.resources.all()):
                        if not r.resource_file:
                            raise ValidationError({
                                input_port: {
                                    index: [
                                        "The resource file of #{0} in the resource list is not ready"
                                        .format(i)
                                    ]
                                }
                            })

                if res.project != serializer.validated_data["workflow"].project:
                    raise ValidationError({
                        input_port: {
                            index: [
                                "Resource or ResourceList is not in the project of Workflow"
                            ]
                        }
                    })
                type_of_res = res.resource_type
                if type_of_res not in types_of_ip:
                    raise ValidationError({
                        input_port: {
                            index: [
                                "The resource type {0} does not match the InputPort {1}"
                                .format(type_of_res, types_of_ip)
                            ]
                        }
                    })

            validated_resource_assignment_dict[ip] = ress

        # Still we have unsatisfied input ports
        if unsatisfied_ips:
            raise ValidationError([
                "There are still unsatisfied InputPorts: {0}".format(" ".join([
                    h_ip.get_url(ip, "inputport-detail", self.request, None)
                    for ip in unsatisfied_ips
                ]))
            ])

        return validated_resource_assignment_dict
예제 #15
0
    def _validate_resource_assignments(self, resource_assignment_dict, serializer):
        """
        Validates the resource assignments

        May throw ValidationError.
        Returns a validated dictionary.
        """
        if not isinstance(resource_assignment_dict, dict):
            raise ValidationError(['This field must be a JSON object'])

        unsatisfied_ips = set(InputPort.objects.filter(workflow_job__in=serializer.validated_data['workflow'].workflow_jobs.all(), connections__isnull=True))
        validated_resource_assignment_dict = {}
        multiple_resource_set = None
        for input_port, resources in resource_assignment_dict.iteritems():
            # 1. InputPort is not satisfied
            h_ip = HyperlinkedIdentityField(view_name="inputport-detail")
            h_ip.queryset = InputPort.objects.all()
            try:
                ip = h_ip.to_internal_value(input_port)
            except ValidationError as e:
                e.detail = {input_port: e.detail}
                raise e

            if ip not in unsatisfied_ips:
                raise ValidationError({input_port: ['Assigned InputPort must be unsatisfied']})
            unsatisfied_ips.remove(ip)
            types_of_ip = ip.input_port_type.resource_types.all()

            # 2. Resources and ResourceLists:
            if not isinstance(resources, list):
                raise ValidationError({input_port: ['A list of resources or resource lists is expected']})

            h_res = HyperlinkedIdentityField(view_name="resource-detail")
            h_res.queryset = Resource.objects.all()
            h_resl = HyperlinkedIdentityField(view_name="resourcelist-detail")
            h_resl.queryset = ResourceList.objects.all()
            ress = []

            for index, r in enumerate(resources):
                try:
                    ress.append(h_res.to_internal_value(r))  # a Resource
                except ValidationError as e:
                    try:
                        ress.append(h_resl.to_internal_value(r))  # a ResourceList
                    except ValidationError as e:
                        e.detail = {input_port: {index: e.detail}}
                        raise e


            ## No empty resource set
            if len(ress) == 0:
                raise ValidationError({input_port: ['It is not allowed to assign an empty resource set']})

            ## There must be at most one multiple resource set
            if len(ress) > 1:
                ress_set = set(map(lambda r: r.uuid, ress))
                if not multiple_resource_set:
                    multiple_resource_set = ress_set
                else:
                    if multiple_resource_set != ress_set:
                        raise ValidationError({input_port: ['It is not allowed to assign multiple resource sets']})

            ## Resource must be in project and resource types are matched
            ## If a ResourceList, it should not be empty and all individuals should satisfy the above requirements.
            for index, res in enumerate(ress):
                if isinstance(res, Resource):
                    if ip.input_port_type.is_list is True:
                        raise ValidationError({input_port: {index: ['The InputPort requires ResourceLists but is provided with Resources']}})
                    if not res.resource_file:
                        raise ValidationError({input_port: {index: ['The resource file is not ready']}})

                else:   # ResourceList
                    if ip.input_port_type.is_list is False:
                        raise ValidationError({input_port: {index: ['The InputPort requires Resources but is provided with ResourceLists']}})

                    for i, r in enumerate(res.resources.all()):
                        if not r.resource_file:
                            raise ValidationError({input_port: {index: ['The resource file of #{0} in the resource list is not ready'.format(i)]}})


                if res.project != serializer.validated_data['workflow'].project:
                    raise ValidationError({input_port: {index: ['Resource or ResourceList is not in the project of Workflow']}})
                type_of_res = res.resource_type
                if type_of_res not in types_of_ip:
                    raise ValidationError({input_port: {index: ['The resource type does not match the InputPort']}})

            validated_resource_assignment_dict[ip] = ress

        # Still we have unsatisfied input ports
        if unsatisfied_ips:
            raise ValidationError(['There are still unsatisfied InputPorts: {0}'.format(
                ' '.join([h_ip.get_url(ip, 'inputport-detail', self.request, None) for ip in unsatisfied_ips])
            )])

        return validated_resource_assignment_dict
예제 #16
0
class NetworkSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name='boxes:network-detail')

    class Meta:
        model = Network
        fields = ('url', 'name', 'description', 'network_url')
예제 #17
0
class RegionSerializer(HyperlinkedModelSerializer):
    uri = HyperlinkedIdentityField(view_name='mygames:region-detail')

    class Meta:
        model = Region
        fields = ('uri', 'region_name', 'tv_format')
예제 #18
0
class TransactionSerializer(serializers.HyperlinkedModelSerializer):
    payment_method = PaymentMethodUrl(view_name='payment-method-detail',
                                      lookup_field='payment_method',
                                      queryset=PaymentMethod.objects.all())
    url = TransactionUrl(view_name='transaction-detail', lookup_field='uuid',)
    pay_url = HyperlinkedIdentityField(view_name='pay-transaction',
                                       lookup_field='uuid',
                                       lookup_url_kwarg='transaction_uuid')
    customer = CustomerUrl(view_name='customer-detail', read_only=True)
    provider = ProviderUrl(view_name='provider-detail', read_only=True)
    id = serializers.CharField(source='uuid', read_only=True)

    class Meta:
        model = Transaction
        fields = ('id', 'url', 'customer', 'provider', 'amount', 'currency',
                  'currency_rate_date', 'state', 'proforma', 'invoice',
                  'can_be_consumed', 'payment_method', 'pay_url', 'valid_until')
        read_only_fields = ('customer', 'provider', 'can_be_consumed', 'pay_url',
                            'id', 'url', 'state')
        write_only_fields = ('valid_until',)

    def validate_proforma(self, proforma):
        if self.instance and proforma != self.instance.proforma:
            message = "This field may not be modified."
            raise serializers.ValidationError(message)

        return proforma

    def validate_invoice(self, invoice):
        if self.instance and invoice != self.instance.invoice:
            message = "This field may not be modified."
            raise serializers.ValidationError(message)
        if (self.instance and getattr(self.instance, 'transactions', None) and
           self.instance.transaction_set.exclude(state='canceled').exists()):
            message = "Cannot update a payment with active transactions."
            raise serializers.ValidationError(message)

        return invoice

    def validate(self, attrs):
        attrs = super(TransactionSerializer, self).validate(attrs)

        if not attrs:
            return attrs

        if self.instance:
            if self.instance.state != Transaction.States.Initial:
                message = "The transaction cannot be modified once it is in {}"\
                          " state.".format(self.instance.state)
                raise serializers.ValidationError(message)

        # Run model clean and handle ValidationErrors
        try:
            # Use the existing instance to avoid unique field errors
            if self.instance:
                transaction = self.instance
                transaction_dict = transaction.__dict__.copy()

                for attribute, value in attrs.items():
                    setattr(transaction, attribute, value)

                transaction.full_clean()

                # Revert changes to existing instance
                transaction.__dict__ = transaction_dict
            else:
                transaction = Transaction(**attrs)
                transaction.full_clean()
        except ValidationError as e:
            errors = e.error_dict
            non_field_errors = errors.pop('__all__', None)
            if non_field_errors:
                errors['non_field_errors'] = [
                    error for sublist in non_field_errors for error in sublist
                ]

            raise serializers.ValidationError(errors)

        return attrs
예제 #19
0
파일: asset.py 프로젝트: iMMAP/ccpm-kpi
class AssetSerializer(serializers.HyperlinkedModelSerializer):

    owner = RelativePrefixHyperlinkedRelatedField(view_name='user-detail',
                                                  lookup_field='username',
                                                  read_only=True)
    owner__username = serializers.ReadOnlyField(source='owner.username')
    url = HyperlinkedIdentityField(lookup_field='uid',
                                   view_name='asset-detail')
    asset_type = serializers.ChoiceField(choices=ASSET_TYPES)
    settings = WritableJSONField(required=False, allow_blank=True)
    content = WritableJSONField(required=False)
    report_styles = WritableJSONField(required=False)
    report_custom = WritableJSONField(required=False)
    map_styles = WritableJSONField(required=False)
    map_custom = WritableJSONField(required=False)
    xls_link = serializers.SerializerMethodField()
    summary = serializers.ReadOnlyField()
    koboform_link = serializers.SerializerMethodField()
    xform_link = serializers.SerializerMethodField()
    version_count = serializers.SerializerMethodField()
    downloads = serializers.SerializerMethodField()
    embeds = serializers.SerializerMethodField()
    parent = RelativePrefixHyperlinkedRelatedField(
        lookup_field='uid',
        queryset=Collection.objects.all(),
        view_name='collection-detail',
        required=False,
        allow_null=True)
    ancestors = AncestorCollectionsSerializer(many=True,
                                              read_only=True,
                                              source='get_ancestors_or_none')
    assignable_permissions = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()
    tag_string = serializers.CharField(required=False, allow_blank=True)
    version_id = serializers.CharField(read_only=True)
    version__content_hash = serializers.CharField(read_only=True)
    has_deployment = serializers.ReadOnlyField()
    deployed_version_id = serializers.SerializerMethodField()
    deployed_versions = PaginatedApiField(
        serializer_class=AssetVersionListSerializer,
        # Higher-than-normal limit since the client doesn't yet know how to
        # request more than the first page
        default_limit=100)
    deployment__identifier = serializers.SerializerMethodField()
    deployment__active = serializers.SerializerMethodField()
    deployment__links = serializers.SerializerMethodField()
    deployment__data_download_links = serializers.SerializerMethodField()
    deployment__submission_count = serializers.SerializerMethodField()
    data = serializers.SerializerMethodField()

    # Only add link instead of hooks list to avoid multiple access to DB.
    hooks_link = serializers.SerializerMethodField()

    class Meta:
        model = Asset
        lookup_field = 'uid'
        fields = (
            'url',
            'owner',
            'owner__username',
            'parent',
            'ancestors',
            'settings',
            'asset_type',
            'date_created',
            'summary',
            'date_modified',
            'version_id',
            'version__content_hash',
            'version_count',
            'has_deployment',
            'deployed_version_id',
            'deployed_versions',
            'deployment__identifier',
            'deployment__links',
            'deployment__active',
            'deployment__data_download_links',
            'deployment__submission_count',
            'report_styles',
            'report_custom',
            'map_styles',
            'map_custom',
            'content',
            'downloads',
            'embeds',
            'koboform_link',
            'xform_link',
            'hooks_link',
            'tag_string',
            'uid',
            'kind',
            'xls_link',
            'name',
            'assignable_permissions',
            'permissions',
            'settings',
            'data',
        )
        extra_kwargs = {
            'parent': {
                'lookup_field': 'uid',
            },
            'uid': {
                'read_only': True,
            },
        }

    def update(self, asset, validated_data):
        asset_content = asset.content
        _req_data = self.context['request'].data
        _has_translations = 'translations' in _req_data
        _has_content = 'content' in _req_data
        if _has_translations and not _has_content:
            translations_list = json.loads(_req_data['translations'])
            try:
                asset.update_translation_list(translations_list)
            except ValueError as err:
                raise serializers.ValidationError(str(err))
            validated_data['content'] = asset_content
        return super().update(asset, validated_data)

    def get_fields(self, *args, **kwargs):
        fields = super().get_fields(*args, **kwargs)
        user = self.context['request'].user
        # Check if the user is anonymous. The
        # django.contrib.auth.models.AnonymousUser object doesn't work for
        # queries.
        if user.is_anonymous:
            user = get_anonymous_user()
        if 'parent' in fields:
            # TODO: remove this restriction?
            fields['parent'].queryset = fields['parent'].queryset.filter(
                owner=user)
        # Honor requests to exclude fields
        # TODO: Actually exclude fields from tha database query! DRF grabs
        # all columns, even ones that are never named in `fields`
        excludes = self.context['request'].GET.get('exclude', '')
        for exclude in excludes.split(','):
            exclude = exclude.strip()
            if exclude in fields:
                fields.pop(exclude)
        return fields

    def get_version_count(self, obj):
        return obj.asset_versions.count()

    def get_xls_link(self, obj):
        return reverse('asset-xls',
                       args=(obj.uid, ),
                       request=self.context.get('request', None))

    def get_xform_link(self, obj):
        return reverse('asset-xform',
                       args=(obj.uid, ),
                       request=self.context.get('request', None))

    def get_hooks_link(self, obj):
        return reverse('hook-list',
                       args=(obj.uid, ),
                       request=self.context.get('request', None))

    def get_embeds(self, obj):
        request = self.context.get('request', None)

        def _reverse_lookup_format(fmt):
            url = reverse('asset-%s' % fmt, args=(obj.uid, ), request=request)
            return {
                'format': fmt,
                'url': url,
            }

        return [
            _reverse_lookup_format('xls'),
            _reverse_lookup_format('xform'),
        ]

    def get_downloads(self, obj):
        def _reverse_lookup_format(fmt):
            request = self.context.get('request', None)
            obj_url = reverse('asset-detail',
                              args=(obj.uid, ),
                              request=request)
            # The trailing slash must be removed prior to appending the format
            # extension
            url = '%s.%s' % (obj_url.rstrip('/'), fmt)

            return {
                'format': fmt,
                'url': url,
            }

        return [
            _reverse_lookup_format('xls'),
            _reverse_lookup_format('xml'),
        ]

    def get_koboform_link(self, obj):
        return reverse('asset-koboform',
                       args=(obj.uid, ),
                       request=self.context.get('request', None))

    def get_data(self, obj):
        kwargs = {'parent_lookup_asset': obj.uid}
        format = self.context.get('format')
        if format:
            kwargs['format'] = format

        return reverse('submission-list',
                       kwargs=kwargs,
                       request=self.context.get('request', None))

    def get_deployed_version_id(self, obj):
        if not obj.has_deployment:
            return
        if isinstance(obj.deployment.version_id, int):
            asset_versions_uids_only = obj.asset_versions.only('uid')
            # this can be removed once the 'replace_deployment_ids'
            # migration has been run
            v_id = obj.deployment.version_id
            try:
                return asset_versions_uids_only.get(
                    _reversion_version_id=v_id).uid
            except AssetVersion.DoesNotExist:
                deployed_version = asset_versions_uids_only.filter(
                    deployed=True).first()
                if deployed_version:
                    return deployed_version.uid
                else:
                    return None
        else:
            return obj.deployment.version_id

    def get_deployment__identifier(self, obj):
        if obj.has_deployment:
            return obj.deployment.identifier

    def get_deployment__active(self, obj):
        return obj.has_deployment and obj.deployment.active

    def get_deployment__links(self, obj):
        if obj.has_deployment and obj.deployment.active:
            return obj.deployment.get_enketo_survey_links()
        else:
            return {}

    def get_deployment__data_download_links(self, obj):
        if obj.has_deployment:
            return obj.deployment.get_data_download_links()
        else:
            return {}

    def get_deployment__submission_count(self, obj):
        if not obj.has_deployment:
            return 0

        try:
            request = self.context['request']
            user = request.user
            if obj.owner_id == user.id:
                return obj.deployment.submission_count

            # `has_perm` benefits from internal calls which use
            # `django_cache_request`. It won't hit DB multiple times
            if obj.has_perm(user, PERM_VIEW_SUBMISSIONS):
                return obj.deployment.submission_count

            if obj.has_perm(user, PERM_PARTIAL_SUBMISSIONS):
                return obj.deployment.calculated_submission_count(
                    requesting_user_id=user.id)
        except KeyError:
            pass

        return 0

    def get_assignable_permissions(self, asset):
        return [{
            'url':
            reverse('permission-detail',
                    kwargs={'codename': codename},
                    request=self.context.get('request')),
            'label':
            asset.get_label_for_permission(codename),
        } for codename in asset.ASSIGNABLE_PERMISSIONS_BY_TYPE[
            asset.asset_type]]

    def get_permissions(self, obj):
        context = self.context
        request = self.context.get('request')

        queryset = ObjectPermissionHelper. \
            get_user_permission_assignments_queryset(obj, request.user)
        # Need to pass `asset` and `asset_uid` to context of
        # AssetPermissionAssignmentSerializer serializer to avoid extra queries to DB
        # within the serializer to retrieve the asset object.
        context['asset'] = obj
        context['asset_uid'] = obj.uid

        return AssetPermissionAssignmentSerializer(queryset.all(),
                                                   many=True,
                                                   read_only=True,
                                                   context=context).data

    def _content(self, obj):
        return json.dumps(obj.content)

    def _table_url(self, obj):
        request = self.context.get('request', None)
        return reverse('asset-table-view', args=(obj.uid, ), request=request)
예제 #20
0
class BaseKeywordSerializer(ModelSerializer):
    url = HyperlinkedIdentityField(view_name="keyword-detail", lookup_field='id')

    class Meta:
        model = categories.Keyword
        fields = ['id', 'name']
예제 #21
0
from rest_framework.fields import SerializerMethodField
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.serializers import ModelSerializer

from comic.models import Comic
from comic.serializers import ComicListSerializer
from users.models import Profile, User, Follower
from users.serializers import UserDetailSerializer, StringSerializer

channel_detail_url = HyperlinkedIdentityField(
    view_name='channel:channel_detail', source=User,
    lookup_field='username', read_only=True
)


class FollowerSerializer(ModelSerializer):
    user = StringSerializer(read_only=True)

    class Meta:
        model = Follower
        fields = [
            'user',
            'timestamp',
        ]


class ChannelListSerializer(ModelSerializer):
    user = StringSerializer(read_only=True)
    follower_count = SerializerMethodField(read_only=True)
    channel_detail_url = channel_detail_url
예제 #22
0
class BaseAgencySerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name="agency-detail", lookup_field='id')
    
    class Meta:
        model = contracts.Agency
        fields = ['id', 'name']
예제 #23
0
class RepositorySerializer(serializers.HyperlinkedModelSerializer):
    measurements = HyperlinkedIdentityField(view_name='measurement-list',
                                            lookup_url_kwarg='repo')

    benchmarks = HyperlinkedIdentityField(view_name='benchmark-list',
                                          lookup_url_kwarg='repo')

    benchmarkdescription = HyperlinkedIdentityField(
        view_name='benchmark_description-list', lookup_url_kwarg='repo')

    allowed_emails = serializers.ListField(child=serializers.CharField(),
                                           required=False,
                                           default=[])

    class Meta:
        model = Repository
        fields = (URL, 'id', 'name', 'organization', 'description', 'topics',
                  'language', 'address', 'allowed_emails', 'measurements',
                  'benchmarks', 'benchmarkdescription', 'token', 'log')
        extra_kwargs = {'token': {'write_only': True}}

    @staticmethod
    def validate_language(value):
        """ Verify the language of the repo is supported """
        if value not in understand_analysis.SUPPORTED_LANGUAGES:
            msg = "Language " + value + " is not supported by understand"
            logger.warning(msg)
            raise serializers.ValidationError(msg)
        return value

    def get_current_user_email(self):
        """ Return the email listed for the current user """
        return get_user_email(self.context.get("request"))

    def create(self, validated_data):

        # Remove token from print version
        print_data = validated_data.copy()
        print_data['token'] = "..."

        log_msg = "Creating repo: " + str(print_data)
        logger.info(log_msg)

        # Clean up common little problems with address
        address = validated_data.get("address")
        if address:
            if address.endswith("/"):
                address = address[:-1]

            if address.endswith(".git"):
                address = address[:-4]

            validated_data["address"] = address

        # Figure out type of repo from address
        validated_data["type"] = get_repo_type(address,
                                               validated_data.get("token"))

        # Add the current user as the only person that can access
        # the new repo til they add more people
        current_user_email = self.get_current_user_email()
        if current_user_email:
            validated_data["allowed_emails"] = [
                current_user_email,
            ]

        # Add in the log string
        validated_data['log'] = log_msg

        # Make the repo per usual
        repo = Repository.objects.create(**validated_data)
        create_history(str(repo.id), current_user_email)
        return repo
예제 #24
0
class BaseContractStatusSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name="contractstatus-detail", lookup_field='code')
    
    class Meta:
        model = contracts.ContractStatus
        fields = ['code', 'name']
예제 #25
0
class TrekListSerializer(DynamicFieldsMixin, serializers.ModelSerializer):
    url = HyperlinkedIdentityField(view_name='apiv2:trek-detail')
    published = serializers.SerializerMethodField(read_only=True)
    geometry = geo_serializers.GeometrySerializerMethodField(read_only=True)
    length_2d = serializers.SerializerMethodField(read_only=True)
    length_3d = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)
    description = serializers.SerializerMethodField(read_only=True)
    description_teaser = serializers.SerializerMethodField(read_only=True)
    difficulty = DifficultySerializer(read_only=True)
    departure = serializers.SerializerMethodField(read_only=True)
    arrival = serializers.SerializerMethodField(read_only=True)
    themes = TrekThemeSerializer(many=True, read_only=True)
    networks = TrekNetworkSerializer(many=True, read_only=True)
    practice = TrekPracticeInTrekSerializer(read_only=True)
    external_id = serializers.SerializerMethodField(read_only=True)
    create_datetime = serializers.SerializerMethodField(read_only=True)
    update_datetime = serializers.SerializerMethodField(read_only=True)

    def get_update_datetime(self, obj):
        return obj.topo_object.date_update

    def get_create_datetime(self, obj):
        return obj.topo_object.date_insert

    def get_published(self, obj):
        return get_translation_or_dict('published', self, obj)

    def get_name(self, obj):
        return get_translation_or_dict('name', self, obj)

    def get_description(self, obj):
        return get_translation_or_dict('description', self, obj)

    def get_departure(self, obj):
        return get_translation_or_dict('departure', self, obj)

    def get_arrival(self, obj):
        return get_translation_or_dict('arrival', self, obj)

    def get_description_teaser(self, obj):
        return get_translation_or_dict('description_teaser', self, obj)

    def get_length_2d(self, obj):
        return round(obj.length_2d_m, 1)

    def get_length_3d(self, obj):
        return round(obj.length_3d_m, 1)

    def get_external_id(self, obj):
        return obj.eid

    def get_geometry(self, obj):
        return obj.geom2d_transformed

    class Meta:
        model = trekking_models.Trek
        fields = (
            'id', 'url', 'name', 'description_teaser',
            'description', 'departure', 'arrival', 'duration',
            'difficulty', 'length_2d', 'length_3d', 'ascent', 'descent',
            'min_elevation', 'max_elevation', 'themes', 'networks', 'practice',
            'external_id', 'published',
            'geometry', 'update_datetime', 'create_datetime'
        )
예제 #26
0
    def _validate_resource_assignments(self, resource_assignment_dict, serializer):
        """
        Validates the resource assignments

        May throw ValidationError.
        Returns a validated dictionary.
        """
        if not isinstance(resource_assignment_dict, dict):
            raise ValidationError(['This field must be a JSON object'])

        unsatisfied_ips = set(InputPort.objects.filter(workflow_job__in=serializer.validated_data['workflow'].workflow_jobs.all(), connections__isnull=True))
        validated_resource_assignment_dict = {}
        multiple_resource_set = None
        for input_port, resources in resource_assignment_dict.iteritems():
            # 1. InputPort is not satisfied
            h_ip = HyperlinkedIdentityField(view_name="inputport-detail")
            h_ip.queryset = InputPort.objects.all()
            try:
                ip = h_ip.to_internal_value(input_port)
            except ValidationError as e:
                e.detail = {input_port: e.detail}
                raise e

            if ip not in unsatisfied_ips:
                raise ValidationError({input_port: ['Assigned InputPort must be unsatisfied']})
            unsatisfied_ips.remove(ip)
            types_of_ip = ip.input_port_type.resource_types.all()

            # 2. Resources and ResourceLists:
            if not isinstance(resources, list):
                raise ValidationError({input_port: ['A list of resources or resource lists is expected']})

            h_res = HyperlinkedIdentityField(view_name="resource-detail")
            h_res.queryset = Resource.objects.all()
            h_resl = HyperlinkedIdentityField(view_name="resourcelist-detail")
            h_resl.queryset = ResourceList.objects.all()
            ress = []

            for index, r in enumerate(resources):
                try:
                    ress.append(h_res.to_internal_value(r))  # a Resource
                except ValidationError as e:
                    try:
                        ress.append(h_resl.to_internal_value(r))  # a ResourceList
                    except ValidationError as e:
                        e.detail = {input_port: {index: e.detail}}
                        raise e


            ## No empty resource set
            if len(ress) == 0:
                raise ValidationError({input_port: ['It is not allowed to assign an empty resource set']})

            ## There must be at most one multiple resource set
            if len(ress) > 1:
                ress_set = set(map(lambda r: r.uuid, ress))
                if not multiple_resource_set:
                    multiple_resource_set = ress_set
                else:
                    if multiple_resource_set != ress_set:
                        raise ValidationError({input_port: ['It is not allowed to assign multiple resource sets']})

            ## Resource must be in project and resource types are matched
            ## If a ResourceList, it should not be empty and all individuals should satisfy the above requirements.
            for index, res in enumerate(ress):
                if isinstance(res, Resource):
                    if ip.input_port_type.is_list is True:
                        raise ValidationError({input_port: {index: ['The InputPort requires ResourceLists but is provided with Resources']}})
                    if not res.resource_file:
                        raise ValidationError({input_port: {index: ['The resource file is not ready']}})

                else:   # ResourceList
                    if ip.input_port_type.is_list is False:
                        raise ValidationError({input_port: {index: ['The InputPort requires Resources but is provided with ResourceLists']}})

                    for i, r in enumerate(res.resources.all()):
                        if not r.resource_file:
                            raise ValidationError({input_port: {index: ['The resource file of #{0} in the resource list is not ready'.format(i)]}})


                if res.project != serializer.validated_data['workflow'].project:
                    raise ValidationError({input_port: {index: ['Resource or ResourceList is not in the project of Workflow']}})
                type_of_res = res.resource_type
                if type_of_res not in types_of_ip:
                    raise ValidationError({input_port: {index: ['The resource type does not match the InputPort']}})

            validated_resource_assignment_dict[ip] = ress

        # Still we have unsatisfied input ports
        if unsatisfied_ips:
            raise ValidationError(['There are still unsatisfied InputPorts: {0}'.format(
                ' '.join([h_ip.get_url(ip, 'inputport-detail', self.request, None) for ip in unsatisfied_ips])
            )])

        return validated_resource_assignment_dict
예제 #27
0
class CompanyiaSerializer(HyperlinkedModelSerializer):
	url = HyperlinkedIdentityField(view_name='iSupermarket:companyia-detail')
	user = CharField(read_only=True)
	class Meta:
		model = Companyia
		fields = ('url', 'name','user')