def test03_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)'), pnt_fld.clean('POINT(5 23)')) self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)')
def test_null(self): "Testing GeometryField's handling of null (None) geometries." # Form fields, by default, are required (`required=True`) fld = forms.GeometryField() with self.assertRaisesMessage(forms.ValidationError, "No geometry value provided."): fld.clean(None) # This will clean None as a geometry (See #10660). fld = forms.GeometryField(required=False) self.assertIsNone(fld.clean(None))
def test_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)'), pnt_fld.clean('POINT(5 23)')) # a WKT for any other geom_type will be properly transformed by `to_python` self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)')) # but rejected by `clean` self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)')
def test02_null(self): "Testing GeometryField's handling of null (None) geometries." # Form fields, by default, are required (`required=True`) fld = forms.GeometryField() self.assertRaises(forms.ValidationError, fld.clean, None) # Still not allowed if `null=False`. fld = forms.GeometryField(required=False, null=False) self.assertRaises(forms.ValidationError, fld.clean, None) # This will clean None as a geometry (See #10660). fld = forms.GeometryField(required=False) self.assertEqual(None, fld.clean(None))
def test_srid(self): "Testing GeometryField with a SRID set." # Input that doesn't specify the SRID is assumed to be in the SRID # of the input field. fld = forms.GeometryField(srid=4326) geom = fld.clean('POINT(5 23)') self.assertEqual(4326, geom.srid) # Making the field in a different SRID from that of the geometry, and # asserting it transforms. fld = forms.GeometryField(srid=32140) tol = 0.0000001 xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140) # The cleaned geometry should be transformed to 32140. cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)') self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))
def test_srid(self): "Testing GeometryField with a SRID set." # Input that doesn't specify the SRID is assumed to be in the SRID # of the input field. fld = forms.GeometryField(srid=4326) geom = fld.clean('POINT(5 23)') self.assertEqual(4326, geom.srid) # Making the field in a different SRID from that of the geometry, and # asserting it transforms. fld = forms.GeometryField(srid=32140) tol = 0.0001 xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140) # The cleaned geometry is transformed to 32140 (the widget map_srid is 3857). cleaned_geom = fld.clean('SRID=3857;POINT (-10615777.40976205 3473169.895707852)') self.assertEqual(cleaned_geom.srid, 32140) self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))
def test_to_python(self): """ to_python() either returns a correct GEOSGeometry object or a ValidationError. """ good_inputs = [ 'POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)', ] bad_inputs = [ 'POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)', '{"type": "FeatureCollection", "features": [' '{"geometry": {"type": "Point", "coordinates": [508375, 148905]}, "type": "Feature"}]}', ] fld = forms.GeometryField() # to_python returns the same GEOSGeometry for a WKT for geo_input in good_inputs: with self.subTest(geo_input=geo_input): self.assertEqual( GEOSGeometry(geo_input, srid=fld.widget.map_srid), fld.to_python(geo_input)) # but raises a ValidationError for any other string for geo_input in bad_inputs: with self.subTest(geo_input=geo_input): with self.assertRaises(ValidationError): fld.to_python(geo_input)
class LocationForm(AttributeModelForm): attributes_field = 'attributes' geometry = gisforms.GeometryField( widget=LeafletWidget(), error_messages={ 'required': __('No map location was provided. Please use the ' 'tools provided on the left side of the map to ' 'mark your new location.') }) type = forms.ChoiceField(choices=filter(lambda c: c[0] != 'PX', ( [('', __('Please select a location type'))] + list(TYPE_CHOICES)))) class Meta: model = SpatialUnit fields = ['geometry', 'type'] def __init__(self, project=None, *args, **kwargs): super().__init__(*args, **kwargs) self.project = project self.add_attribute_fields() def save(self, *args, **kwargs): entity_type = self.cleaned_data['type'] kwargs['entity_type'] = entity_type kwargs['project_id'] = self.project.pk return super().save(*args, **kwargs)
class LocationForm(AttributeModelForm): geometry = gisforms.GeometryField( widget=LeafletWidget(), error_messages={ 'required': _('No map location was provided. Please use the tools ' 'provided on the left side of the map to mark your ' 'new location.') }) type = forms.ChoiceField(choices=filter(lambda c: c[0] != 'PX', ( [('', _('Please select a location type'))] + list(TYPE_CHOICES)))) attributes_field = 'attributes' class Meta: model = SpatialUnit fields = ['geometry', 'type'] def __init__(self, project_id=None, *args, **kwargs): super().__init__(*args, **kwargs) self.project_id = project_id def save(self): instance = super().save(commit=False) instance.project_id = self.project_id instance.save() return instance
def test_init(self): "Testing GeometryField initialization with defaults." fld = forms.GeometryField() for bad_default in ('blah', 3, 'FoO', None, 0): with self.subTest(bad_default=bad_default): with self.assertRaises(ValidationError): fld.clean(bad_default)
def test_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): # `to_python` uses the SRID of OpenLayersWidget if the converted # value doesn't have an SRID itself. self.assertEqual(GEOSGeometry(wkt, srid=fld.widget.map_srid), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)', srid=pnt_fld.widget.map_srid), pnt_fld.clean('POINT(5 23)')) # a WKT for any other geom_type will be properly transformed by `to_python` self.assertEqual( GEOSGeometry('LINESTRING(0 0, 1 1)', srid=pnt_fld.widget.map_srid), pnt_fld.to_python('LINESTRING(0 0, 1 1)') ) # but rejected by `clean` with self.assertRaises(forms.ValidationError): pnt_fld.clean('LINESTRING(0 0, 1 1)')
def test_to_python(self): """ Testing to_python returns a correct GEOSGeometry object or a ValidationError """ fld = forms.GeometryField() # to_python returns the same GEOSGeometry for a WKT for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt)) # but raises a ValidationError for any other string for wkt in ('POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'): self.assertRaises(forms.ValidationError, fld.to_python, wkt)
class BaseSearchForm(forms.Form): """ Basic version of form for basic seaching of django-geospaas metadata """ polygon = forms.GeometryField(label=False, widget=LeafletWidget( attrs={ 'settings_overrides': { 'DEFAULT_CENTER': (89.0, 179.0), 'DEFAULT_ZOOM': 1, 'NO_GLOBALS': False, 'PLUGINS': { 'forms': { 'auto-include': True } }, } }), required=False) time_coverage_start = forms.DateTimeField( initial=timezone.datetime(2000, 1, 1, tzinfo=timezone.utc)) time_coverage_end = forms.DateTimeField(initial=timezone.now()) source = forms.ModelMultipleChoiceField(Source.objects.all(), required=False) def filter(self, ds): """ Filtering method of the form. All filtering processes are coded here """ # filtering based on time t_0 = self.cleaned_data['time_coverage_start'] t_1 = self.cleaned_data['time_coverage_end'] # Too early datasets are excluded from the filtering results ds = ds.exclude(time_coverage_end__lte=t_0) # Too late datasets are excluded from the filtering results ds = ds.exclude(time_coverage_start__gt=t_1) src = self.cleaned_data.get('source', None) # Just the one(s) with correct selected source should pass the filtering actions # if Source is given in the input form if src: ds = ds.filter(source__in=src) # spatial filtering if self.cleaned_data['polygon']: # filtering by user provided polygon ds = ds.filter(geographic_location__geometry__intersects=self. cleaned_data['polygon']) # sorting ds = ds.order_by('time_coverage_start') return ds
def test_to_python_different_map_srid(self): f = forms.GeometryField(widget=OpenLayersWidget) json = '{ "type": "Point", "coordinates": [ 5.0, 23.0 ] }' self.assertEqual(GEOSGeometry('POINT(5 23)', srid=f.widget.map_srid), f.to_python(json))
class FeatureBaseForm(forms.ModelForm): title = forms.CharField(label='Nom', required=True) geom = forms.GeometryField( label="Localisation", required=True, srid=4326, ) class Meta: model = Feature fields = ( 'title', 'description', 'status', 'geom' ) def __init__(self, *args, **kwargs): feature_type = kwargs.pop('feature_type') user = kwargs.pop('user', None) super().__init__(*args, **kwargs) project = feature_type.project # Status choices initial = 'draft' choices = tuple(x for x in Feature.STATUS_CHOICES) if not project.moderation: choices = tuple(x for x in Feature.STATUS_CHOICES if x[0] != 'pending') initial = 'published' if not self.instance else self.instance.status if project.moderation and not Authorization.has_permission(user, 'can_publish_feature', project): choices = tuple(x for x in Feature.STATUS_CHOICES if x[0] in ['draft', 'pending']) initial = 'pending' if project.moderation and Authorization.has_permission(user, 'can_publish_feature', project): choices = tuple(x for x in Feature.STATUS_CHOICES if x[0] in ['draft', 'published', 'archived']) initial = 'draft' self.fields['status'] = forms.ChoiceField( choices=choices, initial=initial, label='Statut' ) # TODO: factoriser les attributs de champs geom # if feature_type.geom_type == "point": # self.fields['geom'] = forms.GeometryField( # label="Localisation", # required=True, # srid=4326, # ) # # if feature_type.geom_type == "linestring": # self.fields['geom'] = forms.LineStringField( # label="Localisation", # required=True, # srid=4326 # ) # # if feature_type.geom_type == "polygon": # self.fields['geom'] = forms.PolygonField( # label="Localisation", # required=True, # srid=4326 # ) def save(self, commit=True, *args, **kwargs): extra = kwargs.pop('extra', None) feature_type = kwargs.pop('feature_type', None) project = kwargs.pop('project', None) creator = kwargs.pop('creator', None) instance = super().save(commit=False) if extra and feature_type: custom_fields = CustomField.objects.filter(feature_type=feature_type) newdict = { field_name: extra.get(field_name) for field_name in custom_fields.values_list('name', flat=True) } stringfied = json.dumps(newdict, cls=DjangoJSONEncoder) instance.feature_data = json.loads(stringfied) if creator: instance.creator = creator if commit: instance.feature_type = feature_type instance.project = project instance.save() return instance
def test00_init(self): "Testing GeometryField initialization with defaults." fld = forms.GeometryField() for bad_default in ('blah', 3, 'FoO', None, 0): self.assertRaises(ValidationError, fld.clean, bad_default)
def __init__(self, *args, **kwargs): super(SpatialQueryForm, self).__init__(*args, **kwargs) for lookup in self.data: if lookup in ALL_TERMS: self.fields[lookup] = forms.GeometryField(required=False) break
def to_internal_value(self, data): # forms.GeometryField cannot handle geojson dicts. if isinstance(data, dict): data = json.dumps(data) return forms.GeometryField().to_python(data)