diff --git a/django/contrib/gis/forms/fields.py b/django/contrib/gis/forms/fields.py
index f806dcb..0b71774 100644
a
|
b
|
class GeometryField(forms.Field):
|
29 | 29 | self.null = kwargs.pop('null', True) |
30 | 30 | super(GeometryField, self).__init__(**kwargs) |
31 | 31 | |
| 32 | def to_python(self, value): |
| 33 | """Transforms the value to a Geometry object.""" |
| 34 | # Trying to create a Geometry object from the form value. |
| 35 | try: |
| 36 | geom = GEOSGeometry(value) |
| 37 | except: |
| 38 | raise forms.ValidationError(self.error_messages['invalid_geom']) |
| 39 | return geom |
| 40 | |
32 | 41 | def clean(self, value): |
33 | 42 | """ |
34 | 43 | Validates that the input value can be converted to a Geometry |
… |
… |
class GeometryField(forms.Field):
|
42 | 51 | else: |
43 | 52 | raise forms.ValidationError(self.error_messages['no_geom']) |
44 | 53 | |
45 | | # Trying to create a Geometry object from the form value. |
46 | | try: |
47 | | geom = GEOSGeometry(value) |
48 | | except: |
49 | | raise forms.ValidationError(self.error_messages['invalid_geom']) |
| 54 | # Transform the value to a python object first |
| 55 | geom = self.to_python(value) |
50 | 56 | |
51 | 57 | # Ensuring that the geometry is of the correct type (indicated |
52 | 58 | # using the OGC string label). |
diff --git a/django/contrib/gis/tests/test_geoforms.py b/django/contrib/gis/tests/test_geoforms.py
index 59fab01..35ef83d 100644
a
|
b
|
class GeometryFieldTest(unittest.TestCase):
|
51 | 51 | |
52 | 52 | pnt_fld = forms.GeometryField(geom_type='POINT') |
53 | 53 | self.assertEqual(GEOSGeometry('POINT(5 23)'), pnt_fld.clean('POINT(5 23)')) |
| 54 | # a WKT for any other geom_type will be properly transformed by `to_python` |
| 55 | self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)')) |
| 56 | # but rejected by `clean` |
54 | 57 | self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)') |
55 | 58 | |
| 59 | def test04_to_python(self): |
| 60 | """ |
| 61 | Testing to_python returns a correct GEOSGeometry object or |
| 62 | a ValidationError |
| 63 | """ |
| 64 | fld = forms.GeometryField() |
| 65 | # to_python returns the same GEOSGeometry for a WKT |
| 66 | for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): |
| 67 | self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt)) |
| 68 | # but raises a ValidationError for any other string |
| 69 | for wkt in ('POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'): |
| 70 | self.assertRaises(forms.ValidationError, fld.to_python, wkt) |
| 71 | |
| 72 | |
56 | 73 | def suite(): |
57 | 74 | s = unittest.TestSuite() |
58 | 75 | s.addTest(unittest.makeSuite(GeometryFieldTest)) |