~ubuntu-branches/ubuntu/jaunty/python-django/jaunty

« back to all changes in this revision

Viewing changes to django/contrib/gis/forms/fields.py

  • Committer: Bazaar Package Importer
  • Author(s): Scott James Remnant, Eddy Mulyono
  • Date: 2008-09-16 12:18:47 UTC
  • mfrom: (1.1.5 upstream) (4.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080916121847-mg225rg5mnsdqzr0
Tags: 1.0-1ubuntu1
* Merge from Debian (LP: #264191), remaining changes:
  - Run test suite on build.

[Eddy Mulyono]
* Update patch to workaround network test case failures.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from django import forms
 
2
from django.contrib.gis.db.backend import SpatialBackend
 
3
from django.utils.translation import ugettext_lazy as _
 
4
 
 
5
class GeometryField(forms.Field):
 
6
    """
 
7
    This is the basic form field for a Geometry.  Any textual input that is
 
8
    accepted by SpatialBackend.Geometry is accepted by this form.  By default, 
 
9
    this is GEOSGeometry, which accepts WKT, HEXEWKB, WKB, and GeoJSON.
 
10
    """
 
11
    widget = forms.Textarea
 
12
 
 
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
    }
 
18
 
 
19
    def __init__(self, **kwargs):
 
20
        self.null = kwargs.pop('null')
 
21
        self.geom_type = kwargs.pop('geom_type')
 
22
        super(GeometryField, self).__init__(**kwargs)
 
23
 
 
24
    def clean(self, value):
 
25
        """
 
26
        Validates that the input value can be converted to a Geometry
 
27
        object (which is returned).  A ValidationError is raised if
 
28
        the value cannot be instantiated as a Geometry.
 
29
        """
 
30
        if not value:
 
31
            if self.null:
 
32
                # The geometry column allows NULL, return None.
 
33
                return None
 
34
            else:
 
35
                raise forms.ValidationError(self.error_messages['no_geom'])
 
36
     
 
37
        try:
 
38
            # Trying to create a Geometry object from the form value.
 
39
            geom = SpatialBackend.Geometry(value)
 
40
        except:
 
41
            raise forms.ValidationError(self.error_messages['invalid_geom'])
 
42
  
 
43
        # Ensuring that the geometry is of the correct type (indicated
 
44
        # using the OGC string label).
 
45
        if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
 
46
            raise forms.ValidationError(self.error_messages['invalid_geom_type'])
 
47
 
 
48
        return geom