Esempio n. 1
0
class CastSerializer(serializers.HyperlinkedModelSerializer):
    destination = GeometryField()
    origin = GeometryField()
    tags = serializers.ListField()

    class Meta:
        model = Cast
Esempio n. 2
0
class PartnerSerializer(GeoFeatureModelSerializer):

    address = GeometryField()
    coverage_area = GeometryField()

    class Meta:
        model = Partner
        fields = '__all__'
        geo_field = 'address'
Esempio n. 3
0
class AreaSerializer(CreateWithUserInCasestudyMixin,
                     NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {'casestudy_pk': 'adminlevel__casestudy__id'}
    casestudy = CasestudyField(source='adminlevel.casestudy',
                               view_name='casestudy-detail')
    point_on_surface = GeometryField(source='pnt', read_only=True)
    geometry = GeometryField(source='geom')

    class Meta:
        model = Area
        fields = ('url', 'id', 'casestudy', 'name', 'code', 'point_on_surface',
                  'geometry', 'inhabitants')
Esempio n. 4
0
class WaysSerializer(HyperlinkedModelSerializer):
    the_geom = GeometryField()

    class Meta:
        model = Ways
        geo_field = 'the_geom'
        fields = ('id', 'the_geom')
Esempio n. 5
0
class CloudSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    timestamp = serializers.DateTimeField(read_only=True)
    user = AccountSerializer(many=False, read_only=True)

    type = serializers.ChoiceField(choices=TYPE_CHOICES)
    position = GeometryField()
    body = serializers.CharField(max_length=400,
                                 validators=[word_filter_validator])

    code = serializers.CharField(required=False,
                                 allow_null=True,
                                 allow_blank=True,
                                 max_length=20,
                                 validators=[word_filter_validator])
    stars = serializers.IntegerField(required=False, allow_null=True)
    expiry = serializers.IntegerField(required=False, allow_null=True)

    votes = VoteSerializer(many=True, read_only=True)

    def create(self, validated_data):
        instance = Cloud.objects.create(**validated_data,
                                        user=self.context['user'])
        instance.save()
        return instance

    class Meta:
        model = Cloud
        exclude = ('visible', )
Esempio n. 6
0
class ServiceAreaSerializer(serializers.ModelSerializer):
    polygon = GeometryField(
        help_text=_("A polygon in GeoJSON, WKT EWKT or HEXEWKB format"))
    provider = serializers.CharField(source='provider.name', read_only=True)

    class Meta:
        model = ServiceArea
        fields = '__all__'
Esempio n. 7
0
class ResourceSerializer(Serializer):
    id = CharField()
    title = CharField()
    description = CharField()
    author = CharField()
    links = ResourceLinkSerializer(many=True)
    created_at = DateTimeField()
    updated_at = DateTimeField()
    geom = GeometryField()
    def test_parsing_valid_values(self):
        field = GeometryField()

        # WKT string
        geom = field.to_internal_value('POINT(1 0)')
        self.assertEqual(geom, GEOSGeometry('POINT(1 0)'))

        # GeoJSON string
        geom = field.to_internal_value('{"type":"Point","coordinates":[1,0]}')
        self.assertEqual(geom, GEOSGeometry('{"type":"Point","coordinates":[1,0]}'))

        # GeoJSON dict
        geom = field.to_internal_value({'type': 'Point', 'coordinates': [1, 0]})
        self.assertEqual(geom, GEOSGeometry('{"type":"Point","coordinates":[1,0]}'))

        # GEOS Geometry
        geom = field.to_internal_value(GEOSGeometry('POINT(1 0)'))
        self.assertEqual(geom, GEOSGeometry('POINT(1 0)'))
Esempio n. 9
0
class RoutingSerializer(HyperlinkedModelSerializer):
    origin = PrimaryKeyRelatedField(read_only=True)
    destination = PrimaryKeyRelatedField(read_only=True)
    geom = GeometryField()

    class Meta:
        model = Routing
        geo_field = 'geom'
        fields = ('url', 'id', 'origin', 'destination', 'geom', 'seq',
                  'distance')
Esempio n. 10
0
class ImageSerializer(serializers.ModelSerializer):
    file = serializers.ImageField(use_url=True)
    location = GeometryField(required=False)

    class Meta:
        model = Image
        fields = (
            'id',
            'file',
            'location',
        )
Esempio n. 11
0
class AreaSerializer(HyperlinkedModelSerializer):
    geom = GeometryField()
    adminlevel = PrimaryKeyRelatedField(read_only=True)
    parent_area = PrimaryKeyRelatedField(read_only=True)
    dataset = PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Area
        geo_field = 'geom'
        fields = ('id', 'adminlevel', 'name', 'code', 'geom', 'parent_area',
                  'inhabitants', 'dataset')
Esempio n. 12
0
class ReportCreateSerializer(serializers.Serializer):
    """
    Serializer for Status object in create action
    This serializer does not use nested status and user object, only id.
    location is the location of the report,that will be mapped/converted to grid ID
    """
    location = GeometryField()
    status = serializers.IntegerField()
    user = serializers.UUIDField()

    class Meta:
        fields = ('status', 'user', 'location')
Esempio n. 13
0
    def test_parsing_invalid_values(self):
        field = GeometryField()

        # Invalid string
        with self.assertRaises(ValidationError):
            geom = field.to_internal_value('No geometry here')

        # Invalid dictionary
        with self.assertRaises(ValidationError):
            geom = field.to_internal_value({'msg': 'No geometry here'})

        # Non-dictionary
        with self.assertRaises(ValidationError):
            geom = field.to_internal_value(['No geometry here'])

        # Non-JSON-encodable obejct
        class CustomObject (object):
            pass

        with self.assertRaises(ValidationError):
            geom = field.to_internal_value(CustomObject())
Esempio n. 14
0
class ProfileSerializer(serializers.ModelSerializer):
    first_name = serializers.CharField(max_length=255, required=False)
    last_name = serializers.CharField(max_length=255, required=False)
    country = CountryField(required=False)
    nationality = CountryField(required=False)
    birthdate = serializers.DateField(required=False)
    location = GeometryField(required=False)

    class Meta:
        model = Profile
        fields = ('first_name', 'last_name', 'full_name', 'country',
                  'nationality', 'birthdate', 'location',
                  'profile_picture_url')
Esempio n. 15
0
class FeatureSerializer(serializers.ModelSerializer):
    geom = GeometryField(validators=[validate_geom])
    properties = serializers.JSONField(required=False)
    relations = serializers.SerializerMethodField()
    geometry_files = serializers.SerializerMethodField()

    def get_geometry_files(self, obj):
        serializer = GeometryFileSerializer(obj)
        return serializer.data

    def get_relations(self, obj):
        return {
            relation.name:
            reverse('feature-relation',
                    args=(obj.layer_id, obj.identifier, relation.pk))
            for relation in obj.layer.relations_as_origin.all()
        }

    def __init__(self, instance=None, data=empty, **kwargs):
        super().__init__(instance=instance, data=data, **kwargs)
        self.layer = None

    def get_layer(self):
        if self.instance:
            self.layer = self.instance.layer
        if not self.layer and self.context.get('layer_pk'):
            self.layer = Layer.objects.get(pk=self.context.get('layer_pk'))
        return self.layer

    def validate_geom(self, data):
        """
        Validate geom exists
        """
        if self.get_layer():
            validate_geom_type(self.get_layer().geom_type, data.geom_typeid)
        return data

    def validate_properties(self, data):
        """
        Validate schema if exists
        """
        if self.get_layer():
            validate_json_schema_data(data, self.get_layer().schema)
        return data

    class Meta:
        model = Feature
        fields = ('id', 'identifier', 'layer', 'geom', 'properties',
                  'relations', 'geometry_files')
        read_only_fields = ('id', 'layer')
Esempio n. 16
0
class SightingsBirdSerializer(serializers.ModelSerializer):
    get_banded_display = serializers.CharField()
    get_sex_guess_display = serializers.CharField()
    get_life_stage_guess_display = serializers.CharField()

    get_bird_display = serializers.StringRelatedField(source='bird',
                                                      many=False)
    sighting = serializers.PrimaryKeyRelatedField(many=False, read_only=True)

    sighting__date_sighted = serializers.ReadOnlyField(
        source='sighting.date_sighted')
    sighting__time_sighted = serializers.ReadOnlyField(
        source='sighting.time_sighted')
    sighting__point_location = GeometryField(source='sighting.point_location')

    class Meta:
        model = SightingsBird
        fields = '__all__'
Esempio n. 17
0
class CountrySerializer(serializers.ModelSerializer):
    # read_only
    capital = CapitalHelperSerializer(read_only=True)
    cities = CityHelperSerializer(source='city_set', read_only=True, many=True)

    # write_only
    capital_ = serializers.PrimaryKeyRelatedField(
        source='capital',
        write_only=True,
        required=False,
        queryset=Capital.objects.all())
    city_set = serializers.PrimaryKeyRelatedField(write_only=True,
                                                  many=True,
                                                  required=False,
                                                  queryset=City.objects.all())
    geometry = GeometryField(write_only=True)

    class Meta:
        model = Country
        fields = [
            'id', 'url', 'name', 'capital', 'cities', 'capital_', 'city_set',
            'geometry'
        ]
Esempio n. 18
0
class ActorSerializer(HyperlinkedModelSerializer):
    geom = GeometryField()
    activity = PrimaryKeyRelatedField(read_only=True)
    process = PrimaryKeyRelatedField(read_only=True)
    company = PrimaryKeyRelatedField(read_only=True)
    dataset = PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Actor
        geo_field = 'geom'
        fields = (
            'url',
            'id',
            'geom',
            'activity',
            'process',
            'identifier',
            'company',
            'postcode',
            'address',
            'city',
            'country',
            'dataset',
        )
Esempio n. 19
0
class CountriesHelperSerializer(serializers.ModelSerializer):
    geometry = GeometryField(write_only=True)

    class Meta:
        model = CountriesHelper
        fields = ['id', 'name', 'geometry']
class NiStDtbPolySerializer(GeoFeatureModelSerializer):
    wkb_geometry = GeometryField()
    class Meta:
        model = NiStDtbPoly
        geo_field = "wkb_geometry"
        fields = ('id_field', 'st_name', 'dt_name', 'wkb_geometry')
Esempio n. 21
0
class GeoWithinSerializer(serializers.Serializer):
    within = GeometryField(required=False)
Esempio n. 22
0
class AreaGeoJsonSerializer(ForceMultiMixin, GeoFeatureModelSerializer,
                            AreaInLevelSerializer):
    """
    Detail serializer for Areas adding the geom field
    and returning a geojson
    """
    adminlevel = AdminLevelField(view_name='adminlevels-detail')
    parent_area = serializers.IntegerField(required=False,
                                           allow_null=True,
                                           source='parent_area.id')
    parent_area_code = serializers.StringRelatedField(
        required=False, allow_null=True, source='parent_area.code')
    parent_level = serializers.IntegerField(read_only=True,
                                            required=False,
                                            allow_null=True,
                                            source='parent_area.adminlevel.id')
    geometry = GeometryField(source='geom')

    class Meta(AreaSerializer.Meta):
        geo_field = 'geometry'
        fields = ('url', 'id', 'casestudy', 'name', 'code', 'adminlevel',
                  'parent_area', 'parent_level', 'parent_area_code',
                  'point_on_surface', 'inhabitants')

    def update(self, instance, validated_data):
        """cast geomfield to multipolygon"""
        self.convert2multi(validated_data, 'geom')
        return super().update(instance, validated_data)

    def create(self, validated_data):
        """Create a new areas"""
        adminlevel = self.get_level(validated_data=validated_data)

        if 'features' not in validated_data:
            parent_area_id = validated_data.pop('parent_area', None)
            # ignore code here
            parent_code = validated_data.pop('parent_area_code', None)
            if (parent_area_id):
                validated_data['parent_area'] = \
                    Area.objects.get(**parent_area_id)
            if isinstance(validated_data['geom'], Polygon):
                validated_data['geom'] = MultiPolygon(validated_data['geom'])
            obj = self.Meta.model.objects.create(adminlevel=adminlevel,
                                                 **validated_data)
            return obj

        parent_level_pk = validated_data.pop('parent_level', None)
        if parent_level_pk is not None:
            parent_adminlevel = AdminLevels.objects.get(level=parent_level_pk)

        for feature in validated_data['features']:
            parent_area_id = feature.pop('parent_area', None)
            parent_area_code = feature.pop('parent_area_code', None)
            if (parent_area_id is not None) and (parent_area_code is not None):
                raise serializers.ValidationError(
                    _("you may only pass parent_area_id OR "
                      "parent_area_code (not both)"))
            self.convert2multi(feature, 'geom')
            obj = Area.objects.create(adminlevel=adminlevel, **feature)
            parent_area = None
            if parent_area_id:
                parent_area = Area.objects.get(**parent_area_id)
                obj.parent_area = parent_area
            if parent_area_code:
                if not parent_level_pk:
                    raise serializers.ValidationError(
                        _("parent_level is required when relating to "
                          "parents by code"))
                parent_area = Area.objects.get(adminlevel=parent_adminlevel,
                                               code=parent_area_code)
            if parent_area:
                obj.parent_area = parent_area
            obj.save()
        return obj

    def get_level(self, validated_data=None):
        validated_data = validated_data or {}
        url_pks = self.context['request'].session['url_pks']
        level_pk = validated_data.pop('level', url_pks['level_pk'])
        adminlevel = AdminLevels.objects.get(pk=level_pk)
        return adminlevel
Esempio n. 23
0
class UserSerializer(serializers.ModelSerializer):
    """
    User serializer.
    """
    last_location = GeometryField(source='location', allow_null=True)
    last_login = TimestampField(read_only=True)
    last_activity = TimestampField(allow_null=True, required=False)
    created_at = TimestampField(source='date_joined', read_only=True)
    phone = serializers.SerializerMethodField()
    avatar_url = serializers.SerializerMethodField()
    age = serializers.SerializerMethodField(read_only=True)
    portfolio = serializers.SerializerMethodField()
    im_confirm_tos = serializers.BooleanField(source='confirm_tos',
                                              write_only=True,
                                              default=False)
    is_contact = serializers.BooleanField(read_only=True)
    is_favorite = serializers.BooleanField(read_only=True)
    is_blocked = serializers.BooleanField(read_only=True)

    class Meta:
        model = get_user_model()
        geo_field = 'location'
        fields = (
            'uuid',
            'display_name',
            'birth_date',
            'email',
            'phone',
            'sex',
            'age',
            'last_login',
            'last_location',
            'created_at',
            'im_confirm_tos',
            'device_id',
            'avatar_uuid',
            'avatar_url',
            'is_contact',
            'is_favorite',
            'is_blocked',
            'is_online',
            'last_activity',
            'show_activity',
            'portfolio',
        )
        extra_kwargs = {
            'avatar_uuid': {
                'write_only': True,
                'required': False
            },
            'email': {
                'write_only': True,
                'required': False
            },
            'device_id': {
                'write_only': True
            },
        }

    def get_portfolio(self, obj):
        qs = obj.files.filter(file_type=File.Type.PORTFOLIO, is_uploaded=True)
        serializers = FileSerializer(qs, many=True)
        return serializers.data

    @staticmethod
    def get_is_online(obj) -> bool:
        if obj.show_activity:
            return obj.is_online
        return False

    def get_last_location(self, obj):
        if obj.show_activity:
            return self.last_location.to_representation(obj.location)
        return None

    def get_phone(self, obj):
        """ Возвращает номер телефона только для текущего пользователя. """
        request = self.context.get('request')
        if request and request.user.is_authenticated and \
                request.user.uuid == obj.uuid:
            return obj.username

    @staticmethod
    def get_avatar_url(obj) -> str:
        if obj.avatar_uuid:
            return obj.get_avatar_url()

    @staticmethod
    def get_age(obj) -> int:
        if obj.birth_date:
            return datetime.utcnow().year - obj.birth_date.year