Exemplo n.º 1
0
class SearchForm(forms.Form):
    postcode = forms.CharField(max_length=50,
                               required=False,
                               help_text="Enter a Post code to search from")
    use_current_location = forms.BooleanField(initial=False, required=False)
    search_radius = forms.IntegerField(min_value=0,
                                       max_value=200,
                                       help_text="Search distance (Miles)")
    maximum_length = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=250,
        help_text="Maximum walk length (Miles)",
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for attribute in Attribute.objects.all():
            self.fields[attribute.attribute] = forms.BooleanField(
                initial=False, required=False)

    def clean(self):
        if (not self.cleaned_data["postcode"]
                and not self.cleaned_data["use_current_location"]):
            raise forms.ValidationError(
                "You must enter a postcode or location or use your current location"
            )
Exemplo n.º 2
0
class RasterTileForm(TileForm):
    band = forms.IntegerField(required=False, initial=1)
    size = forms.IntegerField(required=False, initial=256)
    limits = fields.CommaSepFloatField(required=False)
    style = forms.ChoiceField(choices=[(k, k.lower())
                                       for k in list(colors.colormap)],
                              required=False)

    def clean_band(self):
        return self.cleaned_data['band'] or self.fields['band'].initial
Exemplo n.º 3
0
class RasterTileForm(TileForm):
    band = forms.IntegerField(required=False, initial=1)
    size = forms.IntegerField(required=False, initial=256)
    limits = fields.CommaSepFloatField(required=False)
    style = forms.CharField(required=False)

    def clean_band(self):
        return self.cleaned_data['band'] or self.fields['band'].initial

    def clean_style(self):
        # Mapnik requires string, not unicode, for style names.
        return str(self.cleaned_data['style'])
Exemplo n.º 4
0
class ClusterPointsForm(forms.Form):
    number_of_clusters = forms.IntegerField(
        label='Number of Clusters to Plot',
        min_value=1,
        max_value=10,
        required=False,
        widget=forms.NumberInput(attrs={'class': 'form-control mr-sm-1'}))
Exemplo n.º 5
0
class GeometryQueryForm(QuerySetForm):
    """A form providing GeoQuerySet method arguments."""
    format = forms.CharField(required=False)
    precision = forms.IntegerField(required=False)
    # Tolerance value for geometry simplification
    simplify = forms.FloatField(required=False)
    srs = fields.SpatialReferenceField(required=False)

    def select(self):
        kwargs = {}
        data = self.cleaned_data
        if data['precision'] is not None:
            kwargs.update(precision=data['precision'])
        tolerance, srs, format = map(data.get, ('simplify', 'srs', 'format'))
        srid = getattr(srs, 'srid', None)
        try:
            has_format = self.queryset.has_format(format)
        except AttributeError:
            # Handle default GeoQuerySet.
            try:
                self.queryset = getattr(self.queryset, format)(**kwargs)
            except AttributeError:
                pass
        else:
            if has_format:
                kwargs.update(format=format)
            self.queryset = self.queryset.simplify(tolerance, srid, **kwargs)
Exemplo n.º 6
0
class RasterQueryForm(QuerySetForm):
    """Validates format options for raster data."""
    bbox = fields.BoundingBoxField(required=False)
    format = forms.CharField(required=False)
    g = fields.OGRGeometryField(required=False)
    upload = fields.GeometryFileField(required=False)
    periods = forms.IntegerField(required=False)
    stat = forms.ChoiceField(choices=[
        (choice, ) * 2
        for choice in 'max', 'mean', 'median', 'min', 'std', 'var'
    ],
                             required=False)

    def clean(self):
        """Return cleaned fields as a dict, determine which geom takes
        precedence.
        """
        data = super(RasterQueryForm, self).clean()
        data['g'] = data.pop('upload') or data.pop('bbox') or data.get('g')
        return data

    def select(self):
        format, geom, stat, periods = map(self.cleaned_data.get,
                                          ('format', 'g', 'stat', 'periods'))
        if not geom and format == 'json':
            return
        if format == 'json':
            qs = self.queryset.summarize(geom, stat)
        else:
            qs = self.queryset.warp(format, geom=geom)
        if periods:
            qs = qs.aggregate_periods(periods)
        self.queryset = qs
Exemplo n.º 7
0
class HomeForm(forms.Form):
    name = forms.CharField(
        min_length=1,
        max_length=255,
        strip=True,
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )
    lat = forms.FloatField(
        widget=forms.HiddenInput()
    )
    lng = forms.FloatField(
        widget=forms.HiddenInput()
    )
    radius = forms.IntegerField(
        max_value='1000000000',
        min_value='5',
        widget=forms.NumberInput(attrs={'class': 'form-control'}),
        initial=50
    )
    module = forms.ModelChoiceField(
        widget=forms.RadioSelect,
        queryset=Module.objects.all(),
        empty_label='モジュールを選択',
        required=True
    )

    class Meta:
        labels = {
            'radius': 'Radius',
            'name': 'Name',
            'module': 'Module'
        }
Exemplo n.º 8
0
class GeometryQueryForm(QuerySetForm):
    """A form providing GeoQuerySet method arguments."""
    format = forms.CharField(required=False)
    precision = forms.IntegerField(required=False, initial=4)
    # Tolerance value for geometry simplification
    simplify = forms.FloatField(required=False)
    srs = fields.SpatialReferenceField(required=False)

    def clean_precision(self):
        # Unfortunately initial values are not used as default values.
        return (self.cleaned_data['precision']
                or self.fields['precision'].initial)

    def select(self):
        data = self.cleaned_data
        kwargs = {'precision': data['precision']}
        tolerance, srs, format = map(data.get, ('simplify', 'srs', 'format'))
        srid = getattr(srs, 'srid', None)
        try:
            has_format = self.queryset.has_format(format)
        except AttributeError:
            # Handle default GeoQuerySet.
            try:
                self.queryset = getattr(self.queryset, format)(**kwargs)
            except AttributeError:
                pass
        else:
            if has_format:
                kwargs.update(format=format)
            self.queryset = self.queryset.simplify(tolerance, srid, **kwargs)
Exemplo n.º 9
0
class GeometryQueryForm(QuerySetForm):
    """A form providing GeoQuerySet method arguments."""
    format = fields.GeoFormatField(required=False)
    op = fields.GeoFormatField(required=False)
    precision = forms.IntegerField(required=False)
    # Tolerance value for geometry simplification
    simplify = forms.FloatField(required=False)
    srs = fields.SpatialReferenceField(required=False)

    def select(self):
        kwargs = {}
        data = self.cleaned_data
        tolerance, srs, format = map(data.get, ('simplify', 'srs', 'format'))
        expr = field = query.geo_field(self.queryset).name
        srid = getattr(srs, 'srid', None)
        if srid:
            expr = functions.Transform(expr, srid)
            self.queryset.query.add_context('transformed_srid', srid)
        if data['op']:
            expr = data['op'](expr)
        if data['precision'] is not None:
            kwargs.update(precision=data['precision'])
        if tolerance:
            expr = query.Simplify(expr, tolerance)
        if format:
            expr = format(expr, **kwargs)
        if expr != field:
            attrname = self.data.get('format')
            self.queryset = self.queryset.annotate(**{attrname: expr})
Exemplo n.º 10
0
class ContactarPeticionForm(forms.ModelForm):
    id_peticion = forms.IntegerField(required=False)

    def clean(self):
        cleaned_data = super().clean()
        telefono = cleaned_data.get("telefono")
        email = cleaned_data.get("email")
        if not email and not telefono:
            raise ValidationError(
                "Es necesario un método de contacto: email o teléfono")

    def is_valid(self):
        valid = super(ContactarPeticionForm, self).is_valid()
        if not valid:
            return valid
        if not self.data["email"] and not self.data["telefono"]:
            return False
        return True

    def save(self):
        contacto = super(ContactarPeticionForm, self).save(commit=False)
        contacto.peticion = Peticion.objects.get(
            pk=self.cleaned_data['id_peticion'])
        contacto.fuente = settings.FUENTE
        contacto.save()
        # Se envía un correo donde alquien quiere ayuda a una persona necesitada y solicita el acceso a sus datos.
        enviar_correo_nueva_solicitud_peticion.delay()
        enviar_correo_ofreciendo_ayuda.delay(contacto.pk)
        return contacto

    class Meta:
        model = SolicitudAccesoPeticion
        fields = '__all__'
        exclude = ['peticion', 'codigo_acceso', 'acceso_permitido', 'fuente']
Exemplo n.º 11
0
class OrganizationForm(forms.ModelForm):
    organization_id = forms.IntegerField(required=False,
                                         widget=forms.HiddenInput())

    class Meta:
        model = Organization
        exclude = ['slug']
        labels = {'url': 'URL'}
Exemplo n.º 12
0
class HelpRequestCompleteForm(forms.ModelForm):
    help_with = forms.IntegerField()
    geo_json = forms.CharField(widget=forms.HiddenInput(), required=True)

    def save(self):
        self.instance.track = self.save_track()
        super(HelpRequestCompleteForm, self).save()
        self.save_points()
        self.instance.assign_bikeanjo()

        if self.instance.bikeanjo:
            notify_bikeanjo_about_new_request(self.instance)

        return self.instance

    def save_points(self):
        geo_json = self.cleaned_data.get('geo_json')
        points = []

        for p in geo_json.get('points', []):
            point = models.Point()
            point.helprequest = self.instance
            point.user = self.instance.requester
            point.coords = Point(p.get('coordinates'))
            point.address = p.get('properties').get('address')
            points.append(point)

        self.instance.point_set.bulk_create(points)
        return points

    def save_track(self):
        geo_json = self.cleaned_data.get('geo_json')
        line = geo_json.get('track')

        if not line:
            return

        track = models.Track()
        track.user = self.instance.requester
        track.track = LineString([c for c in line.get('coordinates')])
        track.start = line.get('properties').get('start')
        track.end = line.get('properties').get('end')
        track.save()

        return track

    def clean_geo_json(self):
        if type(self.data['geo_json']) in (list, dict):
            return self.data['geo_json']
        return self.cleaned_data['geo_json']

    class Meta:
        model = models.HelpRequest
        fields = (
            'help_with',
            'message',
        )
Exemplo n.º 13
0
class SearchForm(forms.Form):
    distance = forms.IntegerField(widget=forms.NumberInput(
        attrs={
            'class': 'hidden',
            'required': 'required'
        }))
    address = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'hidden',
        'required': 'required'
    }))
    days = forms.IntegerField(widget=forms.NumberInput(attrs={
        'class': 'hidden',
        'required': 'required'
    }))
    event_types = forms.MultipleChoiceField(
        choices=Event.EVENT_TYPE_CHOICES,
        widget=CheckboxSelectMultipleULAttrs(
            ulattrs='class="list-unstyled hidden event-type-list"'))
Exemplo n.º 14
0
class HelpRequestUpdateForm(forms.ModelForm):
    requester_rating = forms.IntegerField(label=_('New cyclist rating'),
                                          required=False)
    requester_eval = forms.CharField(label=_('New cyclist evaluation'),
                                     required=False)
    reason = forms.CharField(label=_('Reason'),
                             widget=forms.HiddenInput,
                             required=False)

    def save(self, **kwargs):
        data = self.cleaned_data
        req = self.instance
        bikeanjo = req.bikeanjo
        closed_by = data.get('closed_by')
        status = data.get('status')

        if 'status' in self.changed_data:
            if status in ['new', 'canceled']:
                if req.bikeanjo:
                    match, created = req.match_set.get_or_create(
                        bikeanjo=req.bikeanjo)
                    match.rejected_date = now()
                    match.reason = data.get('reason', 'user canceled request')
                    match.save()

                if status == 'new' and closed_by == 'bikeanjo':
                    req.bikeanjo = None

        super(HelpRequestUpdateForm, self).save(self, **kwargs)

        if 'status' in self.changed_data:
            if status in ['attended', 'finalized']:
                enqueue_30days_notification_for_closed_requests(req)
            else:
                dequeue_30days_notification_for_closed_requests(req)

            if status == 'open':
                enqueue_15days_notification_for_open_requests(req)
            else:
                dequeue_15days_notification_for_open_requests(req)

        if data.get('closed_by') == 'bikeanjo':
            if req.status == 'new':
                notify_that_bikeanjo_cannot_help_anymore(req, bikeanjo)
            elif req.status == 'canceled':
                notify_that_bikeanjo_canceled_request_by_inactivity(
                    req, bikeanjo)
            elif req.status == 'attended':
                notify_requester_about_attended_request(req)

        return req

    class Meta:
        model = models.HelpRequest
        fields = ('status', 'requester_eval', 'requester_rating', 'closed_by')
Exemplo n.º 15
0
class HelpOfferForm(forms.ModelForm):
    help_with = forms.IntegerField(label=_('Help with'))

    def get_help_choices(self):
        value = self.instance.help_with
        for code, label in models.HELP_OFFER:
            yield (code, label, bool(value & code))

    class Meta:
        model = models.User
        fields = ('help_with', )
Exemplo n.º 16
0
    def __init__(self, *args, **kwargs):
        extra = kwargs.pop('extra', None)
        feature = kwargs.pop('feature', None)
        super().__init__(*args, **kwargs)

        for custom_field in extra.order_by('position'):
            if custom_field.field_type == 'boolean':
                self.fields[custom_field.name] = forms.BooleanField(
                    label=custom_field.label,
                    initial=False,
                    required=False,
                )

            if custom_field.field_type == 'char':
                self.fields[custom_field.name] = forms.CharField(
                    label=custom_field.label, max_length=256, required=False)

            if custom_field.field_type == 'date':
                self.fields[custom_field.name] = forms.DateField(
                    label=custom_field.label,
                    required=False,
                )

            if custom_field.field_type == 'integer':
                self.fields[custom_field.name] = forms.IntegerField(
                    label=custom_field.label, required=False)

            if custom_field.field_type == 'decimal':
                self.fields[custom_field.name] = forms.DecimalField(
                    label=custom_field.label,
                    required=False,
                    widget=forms.TextInput(attrs={'localization': False}))

            if custom_field.field_type == 'text':
                self.fields[custom_field.name] = forms.CharField(
                    label=custom_field.label,
                    required=False,
                    widget=forms.Textarea())

            if custom_field.field_type == 'list' and custom_field.options:
                self.fields[custom_field.name] = forms.ChoiceField(
                    label=custom_field.label,
                    choices=[(str(xx), str(xx))
                             for xx in custom_field.options],
                    required=False)

            self.fields[custom_field.name].widget.attrs.update(
                {'field_type': custom_field.field_type})

        if feature and isinstance(feature.feature_data, dict):
            for custom_field in extra:
                self.fields[
                    custom_field.name].initial = feature.feature_data.get(
                        custom_field.name)
Exemplo n.º 17
0
class VenueForm(forms.ModelForm):
    venue_id = forms.IntegerField(required=False, widget=forms.HiddenInput())

    class Meta:
        model = Venue
        exclude = ['slug']
        widgets = {'description': forms.Textarea(attrs={'rows': 3})}
        labels = {'title': 'Venue Name', 'url': 'URL'}

    class Media:
        js = ('js/sigo.js', 'js/add-form.js')
Exemplo n.º 18
0
class TileForm(QuerySetForm):
    """Validates requested map tiling parameters."""
    bbox = fields.OGRGeometryField(srid=4326, required=False)
    size = forms.IntegerField(required=False, initial=256)
    x = forms.IntegerField()
    y = forms.IntegerField()
    z = forms.IntegerField()

    def clean(self):
        data = super(TileForm, self).clean()
        x, y, z = map(data.get, ('x', 'y', 'z'))
        # Create bbox from NW and SE tile corners.
        try:
            extent = (tile.to_lonlat(x, y, z) +
                      tile.to_lonlat(x + 1, y + 1, z))
        except ValueError:
            extent = (0, 0, 0, 0)
        geom = gdal.OGRGeometry.from_bbox(extent)
        geom.srid = self.fields['bbox'].srid
        data['bbox'] = geom
        return data
Exemplo n.º 19
0
class PageForm(forms.ModelForm):
    title = forms.CharField(max_length=128, help_text="Please enter the name of the food")
    url = forms.ChoiceField(choices=FOOD_CHOICES, help_text="Please select the type of food it is")
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

    class Meta:
        # Provide an association between the ModelForm and a model
        model = Page
        # What fields do we want to include in our form?
        # This way we don't need every field in the model present.
        # Some fields may allow NULL values, so we may not want to include them… # Here, we are hiding the foreign key.
        fields = ('title', 'url', 'views')
Exemplo n.º 20
0
class EntryForm(forms.Form):
    feedTime = forms.DateTimeField()
    feedType = forms.CharField(max_length=50)
    feedAmt = forms.FloatField()
    flockSize = forms.IntegerField()
    feedLoc = forms.PointField(widget=forms.OSMWidget(
        attrs={
            'map_width': 800,
            'map_height': 500,
            'default_lat': 48.427502,
            'default_lon': -123.367264
        }))
Exemplo n.º 21
0
class SymptonsForm(forms.ModelForm):

    temperature = forms.FloatField(min_value=36,
                                   max_value=45,
                                   help_text='Temperatura corporal',
                                   label='Temperatura',
                                   initial=36.5)
    edad = forms.IntegerField(help_text='Edad actual',
                              label='Edad',
                              initial=False,
                              required=True,
                              min_value=1,
                              max_value=120)
    sexo = forms.ChoiceField(help_text='Género',
                             label='Género',
                             initial=False,
                             required=False,
                             choices=((1, ''), (2, 'Hombre'), (3, 'Mujer')))
    tos = forms.BooleanField(help_text='¿Tienes tos?',
                             label='Tos',
                             initial=False,
                             required=False)
    dolor_cabeza = forms.BooleanField(help_text='¿Tienes dolor de cabeza?',
                                      label='Dolor de Cabeza',
                                      initial=False,
                                      required=False)
    dolor_garganta = forms.BooleanField(help_text='¿Tienes dolor de garganta?',
                                        label='Dolor de garganta',
                                        initial=False,
                                        required=False)
    respiracion = forms.BooleanField(
        help_text='¿Tienes dificultad para respirar?',
        label='Dificultad para Respirar',
        initial=False,
        required=False)
    latitude = forms.FloatField(initial=20, label='Latitud',
                                required=False)  #, disabled='disabled')
    longitude = forms.FloatField(initial=-105,
                                 label='Longitud',
                                 required=False)  #, disabled='disabled')

    # location = SpatialLocationField()

    class Meta:
        model = Person
        fields = [
            'temperature',
            'latitude',
            'longitude',
            'age',
            'sexo',
        ]
Exemplo n.º 22
0
class ContactarPeticionForm(forms.ModelForm):
    id_peticion = forms.IntegerField(required=False)

    def save(self):
        contacto = super(ContactarPeticionForm, self).save(commit=False)
        contacto.peticion = Peticion.objects.get(pk=self.cleaned_data['id_peticion'])
        contacto.save()
        # TODO
        # Enviar notificación solicitando el acceso a los datos de la persona que pide ayuda.
        # Por el momento será un proceso manual
        return contacto

    class Meta:
        model = SolicitudAccesoPeticion
        fields = '__all__'
        exclude = ['peticion', 'codigo_acceso', 'acceso_permitido']
Exemplo n.º 23
0
class ContactarColaboradorForm(forms.ModelForm):
    id_colaborador = forms.IntegerField(required=False)

    def save(self):
        contacto = super(ContactarColaboradorForm, self).save(commit=False)
        contacto.colaborador = Colaborador.objects.get(
            pk=self.cleaned_data['id_colaborador'])
        contacto.save()
        # TODO
        # Enviar notificación solicitando el acceso a los datos del colaborador.
        # Por el momento será un proceso manual
        return contacto

    class Meta:
        model = SolicitudAccesoColaborador
        fields = '__all__'
        exclude = ['colaborador', 'codigo_acceso', 'acceso_permitido']
Exemplo n.º 24
0
class RasterQueryForm(QuerySetForm):
    """Validates format options for raster data."""
    bbox = fields.BoundingBoxField(required=False)
    format = forms.CharField(required=False)
    g = fields.OGRGeometryField(srid=4326, required=False)
    upload = fields.GeometryFileField(required=False)
    periods = forms.IntegerField(required=False)
    stat = forms.ChoiceField(choices=[
        (choice, ) * 2
        for choice in ['count', 'max', 'mean', 'median', 'min', 'std', 'var']
    ],
                             required=False)

    def clean(self):
        """Return cleaned fields as a dict, determine which geom takes
        precedence.
        """
        data = super(RasterQueryForm, self).clean()
        geom = data.pop('upload', None) or data.pop('bbox', None)
        if geom:
            data['g'] = geom
        return data

    def select(self):
        txtformats = (renderers.JSONRenderer.format, CSVRenderer.format)
        htmlformats = (renderers.BrowsableAPIRenderer.format,
                       renderers.TemplateHTMLRenderer.format)
        fields = ('format', 'g', 'stat', 'periods')
        format, geom, stat, periods = map(self.cleaned_data.get, fields)
        if not geom and format in htmlformats + txtformats:
            return
        elif geom and format in htmlformats:
            format = txtformats[0]
        if format in txtformats:
            qs = self.queryset.summarize(geom, stat)
        else:
            qs = self.queryset.warp(format=format, geom=geom)
            if GeoTIFFZipRenderer.format[-3:] in format:
                qs = qs.zipfiles()
        if periods:
            qs = qs.aggregate_periods(periods)
        self.queryset = qs
Exemplo n.º 25
0
class BikeanjoExperienceForm(forms.ModelForm):
    ride_experience = forms.ChoiceField(label=_('Ride experience'),
                                        choices=models.BIKEANJO_EXPERIENCE)
    bike_use = forms.ChoiceField(label=_('Bike use'), choices=models.BIKE_USE)
    initiatives = forms.CharField(label=_('Initiatives'),
                                  required=False,
                                  max_length=256)
    help_with = forms.IntegerField(label=_('Help with'))

    def get_help_choices(self):
        value = self.instance.help_with
        for code, label in models.HELP_OFFER:
            yield (code, label, bool(value & code))

    class Meta:
        model = models.User
        fields = (
            'ride_experience',
            'bike_use',
            'initiatives',
            'help_with',
            'available',
        )
Exemplo n.º 26
0
class HelpRequestForm(forms.ModelForm):
    help_with = forms.IntegerField()

    def __init__(self, *args, **kwargs):
        requester = kwargs.pop('requester')
        super(HelpRequestForm, self).__init__(*args, **kwargs)
        self.instance.requester = requester

        if not requester.accepted_agreement:
            last_request = requester.helprequested_set.first()

            if last_request:
                self.instance = last_request

    def get_help_choices(self):
        for code, label in models.HELP_REQUEST:
            yield (
                code,
                label,
            )

    class Meta:
        model = models.HelpRequest
        fields = ('help_with', )
Exemplo n.º 27
0
class ProjectModelForm(forms.ModelForm):

    title = forms.CharField(label='Titre', max_length=100)

    thumbnail = forms.ImageField(label="Illustration du projet", required=False)

    description = forms.CharField(
        label='Description', required=False, widget=forms.Textarea())

    moderation = forms.BooleanField(label='Modération', required=False)

    is_project_type = forms.BooleanField(
        label="Est un projet type", required=False)

    archive_feature = forms.IntegerField(
        label='Délai avant archivage', required=False)

    delete_feature = forms.IntegerField(
        label='Délai avant suppression', required=False)

    access_level_pub_feature = forms.ModelChoiceField(
        label='Visibilité des signalements publiés',
        queryset=UserLevelPermission.objects.filter(rank__lte=2).order_by('rank'),
        empty_label=None,)

    access_level_arch_feature = forms.ModelChoiceField(
        label='Visibilité des signalements archivés',
        queryset=UserLevelPermission.objects.filter(rank__lte=4).order_by('rank'),
        empty_label=None,)

    create_from = forms.CharField(required=False, widget=HiddenInput())

    class Meta:
        model = Project
        fields = [
            'title',
            'description',
            'moderation',
            'thumbnail',
            'access_level_pub_feature',
            'access_level_arch_feature',
            'archive_feature',
            'delete_feature',
            'is_project_type',
            'create_from',
        ]

    def __init__(self, *args, **kwargs):

        slug = kwargs.pop('create_from', None)
        project_type = Project.objects.filter(slug=slug).first()

        super().__init__(*args, **kwargs)
        instance = kwargs.get('instance')

        if instance:
            # Optionnel
            for key in ['archive_feature', 'delete_feature']:
                source = getattr(instance, key)
                self.fields[key].initial = source
        elif project_type:
            for key in [
                    'archive_feature', 'delete_feature',
                    'access_level_pub_feature', 'access_level_arch_feature',
                    'description', 'moderation', 'thumbnail']:
                source = getattr(project_type, key)
                self.fields[key].initial = source
            self.fields['title'].initial = "{} (Copie-{})".format(
                project_type.title, timezone.now().strftime("%d/%m/%Y %H:%M")
            )
            self.fields['title'].help_text = "Le titre d'un projet doit etre unique. "
            self.fields['create_from'].initial = slug
        else:
            self.fields['archive_feature'].initial = 0
            self.fields['delete_feature'].initial = 0

    def clean_title(self):
        title = self.cleaned_data.get('title')
        if self.instance.pk:
            if Project.objects.filter(title=title).exclude(pk=self.instance.pk).exists():
                msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà."
                raise forms.ValidationError(msg)
        else:
            if Project.objects.filter(title=title).exists():
                msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà."
                raise forms.ValidationError(msg)
        return title

    def clean(self):
        cleaned_data = super().clean()
        archive_feature = cleaned_data.get('archive_feature', None)
        delete_feature = cleaned_data.get('delete_feature', None)
        if archive_feature and delete_feature and archive_feature > delete_feature:
            raise forms.ValidationError({
                'archive_feature': "Le délais de suppression doit être supérieur au délais d'archivage. "
            })
        return cleaned_data
Exemplo n.º 28
0
class SearchProbeExpressionForm(forms.Form):
    search_value = forms.IntegerField(
        label='Search Probe Expression (ProbeName)',
        required=False,
        widget=forms.NumberInput(attrs={'class': 'form-control mr-sm-1'}))
Exemplo n.º 29
0
class RequestForm(geoforms.Form):
    radius = geoforms.IntegerField()
    location = geoforms.PointField(widget=geoforms.OSMWidget(
        {'map_srid': 4326}),
                                   required=True)
Exemplo n.º 30
0
class ProjectModelForm(forms.ModelForm):

    title = forms.CharField(label='Titre', max_length=100)

    thumbnail = forms.ImageField(label="Illustration du projet",
                                 required=False)

    description = forms.CharField(label='Description',
                                  required=False,
                                  widget=forms.Textarea())

    moderation = forms.BooleanField(label='Modération', required=False)

    archive_feature = forms.IntegerField(label='Délai avant archivage',
                                         required=False)

    delete_feature = forms.IntegerField(label='Délai avant suppression',
                                        required=False)

    access_level_pub_feature = forms.ModelChoiceField(
        label='Visibilité des signalements publiés',
        queryset=UserLevelPermission.objects.filter(
            rank__lte=2).order_by('rank'),
        empty_label=None,
    )

    access_level_arch_feature = forms.ModelChoiceField(
        label='Visibilité des signalements archivés',
        queryset=UserLevelPermission.objects.filter(
            rank__lte=4).order_by('rank'),
        empty_label=None,
    )

    class Meta:
        model = Project
        fields = [
            'title',
            'description',
            'moderation',
            'thumbnail',
            'access_level_pub_feature',
            'access_level_arch_feature',
            'archive_feature',
            'delete_feature',
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        instance = kwargs.get('instance')

        if instance:
            self.fields['archive_feature'].initial = instance.archive_feature
            self.fields['delete_feature'].initial = instance.delete_feature
        else:
            self.fields['archive_feature'].initial = 0
            self.fields['delete_feature'].initial = 0

    def clean_title(self):
        title = self.cleaned_data.get('title')
        if self.instance.pk:
            if Project.objects.filter(title=title).exclude(
                    pk=self.instance.pk).exists():
                msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà."
                raise forms.ValidationError(msg)
        else:
            if Project.objects.filter(title=title).exists():
                msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà."
                raise forms.ValidationError(msg)
        return title

    def clean(self):
        cleaned_data = super().clean()
        archive_feature = cleaned_data.get('archive_feature', None)
        delete_feature = cleaned_data.get('delete_feature', None)
        if archive_feature and delete_feature and archive_feature > delete_feature:
            raise forms.ValidationError(
                "Le délai d'archivage doit être inférieur au délai de suppression. "
            )
        return cleaned_data