PageRenderTime 25ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/gis/forms/fields.py

https://code.google.com/p/mango-py/
Python | 67 lines | 38 code | 9 blank | 20 comment | 12 complexity | 260d1a002a18ec299d4ea4e654316015 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from django import forms
  2. from django.utils.translation import ugettext_lazy as _
  3. # While this couples the geographic forms to the GEOS library,
  4. # it decouples from database (by not importing SpatialBackend).
  5. from django.contrib.gis.geos import GEOSGeometry
  6. class GeometryField(forms.Field):
  7. """
  8. This is the basic form field for a Geometry. Any textual input that is
  9. accepted by GEOSGeometry is accepted by this form. By default,
  10. this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON.
  11. """
  12. widget = forms.Textarea
  13. default_error_messages = {
  14. 'no_geom' : _(u'No geometry value provided.'),
  15. 'invalid_geom' : _(u'Invalid geometry value.'),
  16. 'invalid_geom_type' : _(u'Invalid geometry type.'),
  17. 'transform_error' : _(u'An error occurred when transforming the geometry '
  18. 'to the SRID of the geometry form field.'),
  19. }
  20. def __init__(self, **kwargs):
  21. # Pop out attributes from the database field, or use sensible
  22. # defaults (e.g., allow None).
  23. self.srid = kwargs.pop('srid', None)
  24. self.geom_type = kwargs.pop('geom_type', 'GEOMETRY')
  25. self.null = kwargs.pop('null', True)
  26. super(GeometryField, self).__init__(**kwargs)
  27. def clean(self, value):
  28. """
  29. Validates that the input value can be converted to a Geometry
  30. object (which is returned). A ValidationError is raised if
  31. the value cannot be instantiated as a Geometry.
  32. """
  33. if not value:
  34. if self.null and not self.required:
  35. # The geometry column allows NULL and is not required.
  36. return None
  37. else:
  38. raise forms.ValidationError(self.error_messages['no_geom'])
  39. # Trying to create a Geometry object from the form value.
  40. try:
  41. geom = GEOSGeometry(value)
  42. except:
  43. raise forms.ValidationError(self.error_messages['invalid_geom'])
  44. # Ensuring that the geometry is of the correct type (indicated
  45. # using the OGC string label).
  46. if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
  47. raise forms.ValidationError(self.error_messages['invalid_geom_type'])
  48. # Transforming the geometry if the SRID was set.
  49. if self.srid:
  50. if not geom.srid:
  51. # Should match that of the field if not given.
  52. geom.srid = self.srid
  53. elif self.srid != -1 and self.srid != geom.srid:
  54. try:
  55. geom.transform(self.srid)
  56. except:
  57. raise forms.ValidationError(self.error_messages['transform_error'])
  58. return geom