def setUp(self): self.f = SnappedLineStringField() self.wktgeom = ('LINESTRING(-0.77054223313507 -5.32573853776343,' '-0.168053647782867 -4.66595028627023)') self.geojson = ('{"type":"LineString","coordinates":[' ' [-0.77054223313507,-5.32573853776343],' ' [-0.168053647782867,-4.66595028627023]]}')
class PathForm(CommonForm): geom = SnappedLineStringField() reverse_geom = forms.BooleanField(required=False, label=_("Reverse path"), help_text=_("The path will be reversed once saved")) geomfields = ['geom'] class Meta(CommonForm.Meta): model = Path fields = CommonForm.Meta.fields + \ ['structure', 'name', 'stake', 'comfort', 'departure', 'arrival', 'comments', 'source', 'networks', 'usages', 'valid', 'draft', 'reverse_geom', 'geom'] def __init__(self, *args, **kwargs): super(PathForm, self).__init__(*args, **kwargs) if self.instance.pk: if not self.instance.draft: # Prevent to set a path as draft again (it could be used by a topology) del self.fields['draft'] if not self.user.has_perm('core.change_path'): del self.fields['draft'] else: if not self.user.has_perm('core.add_draft_path') or not self.user.has_perm('core.add_path'): del self.fields['draft'] self.fields['geom'].label = '' def clean_geom(self): pk = self.instance.pk if self.instance and self.instance.pk else -1 geom = self.cleaned_data['geom'] if geom is None: raise forms.ValidationError(_("Invalid snapped geometry.")) if not geom.simple: raise forms.ValidationError(_("Geometry is not simple.")) if not PathHelper.disjoint(geom, pk): raise forms.ValidationError(_("Geometry overlaps another.")) return geom def save(self, commit=True): path = super(PathForm, self).save(commit=False) if not self.instance.pk: if self.user.has_perm('core.add_draft_path') and not self.user.has_perm('core.add_path'): path.draft = True if not self.user.has_perm('core.add_draft_path') and self.user.has_perm('core.add_path'): path.draft = False if self.cleaned_data.get('reverse_geom'): path.reverse() if commit: path.save() self.save_m2m() return path
def test_snappedlinestring(self): f = SnappedLineStringField() self.assertRaises(ValidationError, f.clean, ('LINESTRING(0 0, 1 0)', )) self.assertRaises(ValidationError, f.clean, ('{"geom": "LINESTRING(0 0, 1 0)"}', )) self.assertRaises( ValidationError, f.clean, ('{"geom": "LINESTRING(0 0, 1 0)", "snap": [null]}', )) self.assertRaises( ValidationError, f.clean, ('{"geom": "LINEPPRING(0 0, 1 0)", "snap": [null, null]}', )) value = '{"geom": "LINESTRING(-0.77054223313507 -5.32573853776343,-0.168053647782867 -4.66595028627023)", "snap": [null, null]}' self.assertTrue( f.clean(value).equals_exact( LineString((100000, 100000), (200000, 200000), srid=settings.SRID), 0.1)) path = PathFactory.create() value = '{"geom": "LINESTRING(-0.77054223313507 -5.32573853776343,-0.168053647782867 -4.66595028627023)", "snap": [null, %s]}' % path.pk self.assertTrue( f.clean(value).equals_exact( LineString((100000, 100000), (2, 2), srid=settings.SRID), 0.1))