Skip to content

Commit 78a49f6

Browse files
[geo] Restrict to points only #151
Fixed the issue by adding a clean method to the location model. This method ensures that when the geometry is not None, it should be an instance of a Point Geometry else a ValidationError is raised Fixes #151
1 parent 11ca7f7 commit 78a49f6

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

openwisp_controller/geo/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
from django.contrib.gis.db import models
2+
from django.contrib.gis.geos import Point
3+
from django.core.exceptions import ValidationError
4+
from django.utils.translation import ugettext_lazy as _
25
from django_loci.base.models import AbstractFloorPlan, AbstractLocation, AbstractObjectLocation
36

47
from openwisp_users.mixins import OrgMixin, ValidateOrgMixin
@@ -8,6 +11,11 @@ class Location(OrgMixin, AbstractLocation):
811
class Meta(AbstractLocation.Meta):
912
abstract = False
1013

14+
def clean(self):
15+
if self.geometry is not None and not isinstance(self.geometry, Point):
16+
raise ValidationError({'geometry': _('Only point geometry is allowed')})
17+
super().clean()
18+
1119

1220
class FloorPlan(OrgMixin, AbstractFloorPlan):
1321
location = models.ForeignKey(Location, models.CASCADE)

openwisp_controller/geo/tests/test_models.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from django.contrib.gis.geos import LineString, Point, Polygon
12
from django.core.exceptions import ValidationError
23
from django.test import TestCase
34
from django_loci.tests.base.test_models import BaseTestModels
@@ -23,3 +24,21 @@ def test_floorplan_location_validation(self):
2324
self.assertIn('location', e.message_dict)
2425
else:
2526
self.fail('ValidationError not raised')
27+
28+
def test_add_location_with_point_geometry(self):
29+
self._create_location(geometry=Point(0, 0, srid=4326), name='point')
30+
obj = self.location_model.objects.get(name='point')
31+
self.assertEqual(obj.name, 'point')
32+
33+
def test_add_location_with_line_geometry(self):
34+
with self.assertRaisesMessage(ValidationError, 'Only point geometry is allowed'):
35+
self._create_location(geometry=LineString((0, 0), (1, 1), srid=4326), name='line')
36+
obj = self.location_model.objects.filter(name='line')
37+
self.assertEqual(obj.count(), 0)
38+
39+
def tes_add_location_with_polygon_geometry(self):
40+
with self.assertRaisesMessage(ValidationError, 'Only point geometry is allowed'):
41+
poly = Polygon((0, 0), (0, 1), (1, 1), (1, 0), (0, 0), srid=4326)
42+
self._create_location(geometry=poly, name='poly')
43+
obj = self.location_model.objects.filter(name='poly')
44+
self.assertEqual(obj.count(), 0)

0 commit comments

Comments
 (0)