class InterventionBaseForm(CommonForm): infrastructure = forms.ModelChoiceField( required=False, queryset=Infrastructure.objects.existing(), widget=forms.HiddenInput()) signage = forms.ModelChoiceField(required=False, queryset=Signage.objects.existing(), widget=forms.HiddenInput()) length = FloatField(required=False, label=_("Length")) project = forms.ModelChoiceField(required=False, label=_("Project"), queryset=Project.objects.existing()) geomfields = ['topology'] leftpanel_scrollable = False topology = TopologyField(label="") fieldslayout = [ Div( HTML(""" <ul class="nav nav-tabs"> <li id="tab-main" class="active"><a href="#main" data-toggle="tab"><i class="icon-certificate"></i> %s</a></li> <li id="tab-advanced"><a href="#advanced" data-toggle="tab"><i class="icon-tasks"></i> %s</a></li> </ul>""" % (_("Main"), _("Advanced"))), Div( Div('structure', 'name', 'date', 'status', 'disorders', 'type', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'description', 'infrastructure', 'signage', css_id="main", css_class="tab-pane active"), Div( 'material_cost', 'heliport_cost', 'subcontract_cost', Fieldset(_("Mandays")), css_id= "advanced", # used in Javascript for activating tab if error css_class="tab-pane"), css_class="scrollable tab-content"), css_class="tabbable"), ] class Meta(CommonForm.Meta): model = Intervention fields = CommonForm.Meta.fields + \ ['structure', 'name', 'date', 'status', 'disorders', 'type', 'description', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'infrastructure', 'signage', 'material_cost', 'heliport_cost', 'subcontract_cost', 'topology']
class BladeForm(CommonForm): topology = TopologyField(label="") geomfields = ['topology'] leftpanel_scrollable = True def __init__(self, *args, **kwargs): super(BladeForm, self).__init__(*args, **kwargs) self.helper.form_tag = False if not self.instance.pk: self.signage = kwargs.get('initial', {}).get('signage') self.helper.form_action += '?signage=%s' % self.signage.pk else: self.signage = self.instance.signage self.fields['topology'].initial = self.signage self.fields['topology'].widget.modifiable = True self.fields['topology'].label = '%s%s %s' % ( self.instance.signage_display, _("On %s") % _(self.signage.kind.lower()), '<a href="%s">%s</a>' % (self.signage.get_detail_url(), str(self.signage))) value_max = self.signage.blade_set.existing().aggregate( max=Max('number'))['max'] if settings.BLADE_CODE_TYPE == int: if not value_max: self.fields['number'].initial = "1" elif value_max.isdigit(): self.fields['number'].initial = str(int(value_max) + 1) elif settings.BLADE_CODE_TYPE is str: if not value_max: self.fields['number'].initial = "A" elif len(value_max) == 1 and "A" <= value_max[0] < "Z": self.fields['number'].initial = chr(ord(value_max[0]) + 1) def save(self, *args, **kwargs): self.instance.set_topology(self.signage) self.instance.signage = self.signage self.instance.structure = self.signage.structure return super(CommonForm, self).save(*args, **kwargs) def clean_number(self): blades = self.signage.blade_set.existing() if self.instance.pk: blades = blades.exclude(number=self.instance.number) already_used = ', '.join([ str(number) for number in blades.values_list('number', flat=True) ]) if blades.filter(number=self.cleaned_data['number']).exists(): raise forms.ValidationError( _("Number already exists, numbers already used : %s" % already_used)) return self.cleaned_data['number'] class Meta: model = Blade fields = [ 'id', 'number', 'direction', 'type', 'condition', 'color' ]
class BaseBladeForm(CommonForm): topology = TopologyField(label="") geomfields = ['topology'] fieldslayout = [ Div( 'number', 'direction', 'type', 'condition', 'color', Fieldset(_('Lines')), ) ] def __init__(self, *args, **kwargs): super(BaseBladeForm, self).__init__(*args, **kwargs) self.helper.form_tag = False if not self.instance.pk: self.signage = kwargs.get('initial', {}).get('signage') self.helper.form_action += '?signage=%s' % self.signage.pk else: self.signage = self.instance.signage value_max = self.signage.blade_set.all().aggregate( max=Max('number'))['max'] if settings.BLADE_CODE_TYPE == int: if not value_max: self.fields['number'].initial = "1" elif value_max.isdigit(): self.fields['number'].initial = str(int(value_max) + 1) elif settings.BLADE_CODE_TYPE is str: if not value_max: self.fields['number'].initial = "A" elif len(value_max) == 1 and "A" <= value_max[0] < "Z": self.fields['number'].initial = chr(ord(value_max[0]) + 1) def save(self, *args, **kwargs): self.instance.set_topology(self.signage) self.instance.signage = self.signage return super(CommonForm, self).save(*args, **kwargs) def clean_number(self): blades = self.signage.blade_set.all() if self.instance.pk: blades = blades.exclude(number=self.instance.number) already_used = ', '.join([ str(number) for number in blades.values_list('number', flat=True) ]) if blades.filter(number=self.cleaned_data['number']).exists(): raise forms.ValidationError( _("Number already exists, numbers already used : %s" % already_used)) return self.cleaned_data['number'] class Meta: model = Blade fields = ['id', 'number', 'direction', 'type', 'condition', 'color']
class TopologyForm(CommonForm): """ This form is a bit specific : We use an extra field (topology) in order to edit the whole model instance. The whole instance, because we use concrete inheritance for topology models. Thus, at init, we load the instance into field, and at save, we save the field into the instance. The geom field is fully ignored, since we edit a topology. """ topology = TopologyField(label="") geomfields = ['topology'] class Meta(CommonForm.Meta): fields = CommonForm.Meta.fields + ['topology'] def __init__(self, *args, **kwargs): super(TopologyForm, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.fields['topology'].initial = self.instance def clean(self, *args, **kwargs): data = super(TopologyForm, self).clean() # geom is computed at db-level and never edited if 'geom' in self.errors: del self.errors['geom'] return data def save(self, *args, **kwargs): topology = self.cleaned_data.pop('topology') instance = super(TopologyForm, self).save(*args, **kwargs) was_edited = instance.pk != topology.pk if was_edited: instance.mutate(topology) return instance
class InterventionForm(CommonForm): """ An intervention can be a Point or a Line """ topology = TopologyField(label="") length = FloatField(required=False, label=_("Length")) project = forms.ModelChoiceField(required=False, label=_("Project"), queryset=Project.objects.existing()) geomfields = ['topology'] leftpanel_scrollable = False fieldslayout = [ Div( HTML(""" <ul class="nav nav-tabs"> <li id="tab-main" class="active"><a href="#main" data-toggle="tab"><i class="icon-certificate"></i> %s</a></li> <li id="tab-advanced"><a href="#advanced" data-toggle="tab"><i class="icon-tasks"></i> %s</a></li> </ul>""" % (_("Main"), _("Advanced"))), Div( Div('structure', 'name', 'date', 'status', 'disorders', 'type', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'description', css_id="main", css_class="tab-pane active"), Div( 'material_cost', 'heliport_cost', 'subcontract_cost', Fieldset(_("Mandays")), css_id= "advanced", # used in Javascript for activating tab if error css_class="tab-pane"), css_class="scrollable tab-content"), css_class="tabbable"), ] class Meta(CommonForm.Meta): model = Intervention fields = CommonForm.Meta.fields + \ ['structure', 'name', 'date', 'status', 'disorders', 'type', 'description', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'material_cost', 'heliport_cost', 'subcontract_cost', 'topology'] def __init__(self, *args, target_type=None, target_id=None, **kwargs): super(InterventionForm, self).__init__(*args, **kwargs) if not self.instance.pk: # New intervention. We have to set its target. if target_type and target_id: # Point target to an existing topology ct = ContentType.objects.get_for_id(target_type) self.instance.target = ct.get_object_for_this_type( id=target_id) # Set POST URL self.helper.form_action += '?target_type={}&target_id={}'.format( target_type, target_id) else: # Point target to a new topology self.instance.target = Topology(kind='INTERVENTION') # Else: existing intervention. Target is already set self.fields['topology'].initial = self.instance.target if self.instance.target.__class__ == Topology: # Intervention has its own topology title = _("On {}".format(_("Paths"))) self.fields['topology'].label = \ '<img src="{prefix}images/path-16.png" title="{title}">{title}'.format( prefix=settings.STATIC_URL, title=title ) else: # Intervention on an existing topology icon = self.instance.target._meta.model_name title = _("On {}".format(str(self.instance.target))) self.fields['topology'].label = \ '<img src="{prefix}images/{icon}-16.png" title="{title}"><a href="{url}">{title}</a>'.format( prefix=settings.STATIC_URL, icon=icon, title=title, url=self.instance.target.get_detail_url() ) # Topology is readonly del self.fields['topology'] # Length is not editable in AltimetryMixin self.fields['length'].initial = self.instance.length editable = bool(self.instance.geom and (self.instance.geom.geom_type == 'Point' or self.instance.geom.geom_type == 'LineString')) self.fields['length'].widget.attrs['readonly'] = editable def save(self, *args, **kwargs): target = self.instance.target if not target.pk: target.save() topology = self.cleaned_data.get('topology') if topology and topology.pk != target.pk: target.mutate(topology) intervention = super().save(*args, **kwargs, commit=False) intervention.target = target intervention.save() self.save_m2m() return intervention
class InterventionForm(CommonForm): """ An intervention can be a Point or a Line """ topology = TopologyField(label="") infrastructure = forms.ModelChoiceField( required=False, queryset=BaseInfrastructure.objects.existing(), widget=forms.HiddenInput()) length = FloatField(required=False, label=_("Length")) leftpanel_scrollable = False fieldslayout = [ Div( HTML(""" <ul class="nav nav-tabs"> <li id="tab-main" class="active"><a href="#main" data-toggle="tab"><i class="icon-certificate"></i> %s</a></li> <li id="tab-advanced"><a href="#advanced" data-toggle="tab"><i class="icon-tasks"></i> %s</a></li> </ul>""" % (unicode(_("Main")), unicode(_("Advanced")))), Div( Div('name', 'date', 'status', 'disorders', 'type', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'description', 'infrastructure', 'pk', 'model', css_id="main", css_class="tab-pane active"), Div( 'material_cost', 'heliport_cost', 'subcontract_cost', Fieldset(_("Mandays")), css_id= "advanced", # used in Javascript for activating tab if error css_class="tab-pane"), css_class="scrollable tab-content"), css_class="tabbable"), ] geomfields = ['topology'] class Meta(CommonForm.Meta): model = Intervention fields = CommonForm.Meta.fields + \ ['structure', 'name', 'date', 'status', 'disorders', 'type', 'description', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'infrastructure', 'material_cost', 'heliport_cost', 'subcontract_cost', 'topology'] def __init__(self, *args, **kwargs): super(InterventionForm, self).__init__(*args, **kwargs) # If we create or edit an intervention on infrastructure, set # topology field as read-only infrastructure = kwargs.get('initial', {}).get('infrastructure') if self.instance.on_infrastructure: infrastructure = self.instance.infrastructure self.fields['infrastructure'].initial = infrastructure if infrastructure: self.helper.form_action += '?infrastructure=%s' % infrastructure.pk self.fields['topology'].required = False self.fields['topology'].widget = TopologyReadonlyWidget() self.fields['topology'].label = '%s%s %s' % ( self.instance.infrastructure_display, unicode(_("On %s") % _(infrastructure.kind.lower())), u'<a href="%s">%s</a>' % (infrastructure.get_detail_url(), unicode(infrastructure))) # Length is not editable in AltimetryMixin self.fields['length'].initial = self.instance.length editable = bool(self.instance.geom and self.instance.geom.geom_type == 'Point') self.fields['length'].widget.attrs['readonly'] = editable def clean(self, *args, **kwargs): # If topology was read-only, topology field is empty, get it from infra. cleaned_data = super(InterventionForm, self).clean() topology_readonly = self.cleaned_data.get('topology', None) is None if topology_readonly and 'infrastructure' in self.cleaned_data: self.cleaned_data['topology'] = self.cleaned_data['infrastructure'] return cleaned_data def save(self, *args, **kwargs): self.instance.length = self.cleaned_data.get('length') infrastructure = self.cleaned_data.get('infrastructure') if infrastructure: self.instance.set_infrastructure(infrastructure) return super(InterventionForm, self).save(*args, **kwargs)
def setUp(self): self.f = TopologyField()