class SubscriptionPreviewForm(forms.Form):
    center = forms.PointField(
        help_text="With the radius, determines the notification area.",
        srid=4326)
    radius = DistanceField(min_value=D(ft=100),
                           max_value=D(mi=1),
                           initial=D(ft=300))
    region_name = forms.ChoiceField(choices=(("Somerville, MA",
                                              "Somerville, MA"), ),
                                    initial=settings.GEO_REGION)
    start = forms.DateTimeField(widget=admin_widgets.AdminDateWidget(),
                                help_text="Find changes since this date")
    end = forms.DateTimeField(widget=admin_widgets.AdminDateWidget(),
                              help_text="Find changes up to this date")

    class Media:
        js = js_files()

    def clean(self):
        cleaned = super().clean()

        if cleaned["start"] >= cleaned["end"]:
            self.add_error("start",
                           ValidationError("start should be less than end"))
            self.add_error("end",
                           ValidationError("end should be greater than start"))

        try:
            center = cleaned["center"]
            cleaned["address"] = Geocoder.reverse_geocode(
                center.y, center.x).split(",")[0]
        except:
            cleaned["address"] = None

        return cleaned
Esempio n. 2
0
class WaternetImporterForm(forms.ModelForm):
    geo_location = CustomPointField()
    lastupdate = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%f%z'])
    lastmoved = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%f%z'],
                                    required=False)

    class Meta:
        model = Waternet
        fields = list(constants.WATERNET_RAW_TO_MODEL_MAPPING.values())
class ConfirmedCaseFormOld(forms.Form):
    location = PointField(label='Approximate Current Residence')
    estimated_date_contracted = forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'],
        widget=XDSoftDateTimePickerInput(),
        label='Estimated Date Contracted')
    date_confirmed = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'],
                                         widget=XDSoftDateTimePickerInput(),
                                         label='Date Confirmed')
    additional_info = forms.CharField(widget=forms.Textarea,
                                      label='Additional Information')
    contagion_sites = MultiPointField(
        label='Locations Visited Since Contraction')
class ContagionSiteForm(forms.Form):
    location = PointField(
        label='Possible Contagion Site'
    )
    start_time = forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'],
        widget=XDSoftDateTimePickerInput(),
        label = 'Start Time'
    )
    end_time = forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'],
        widget=XDSoftDateTimePickerInput(),
        label = 'End Time'
    )
Esempio n. 5
0
class BaseSearchForm(forms.Form):
    """ Basic version of form for basic seaching of django-geospaas metadata """
    polygon = forms.GeometryField(label=False,
                                  widget=LeafletWidget(
                                      attrs={
                                          'settings_overrides': {
                                              'DEFAULT_CENTER': (89.0, 179.0),
                                              'DEFAULT_ZOOM': 1,
                                              'NO_GLOBALS': False,
                                              'PLUGINS': {
                                                  'forms': {
                                                      'auto-include': True
                                                  }
                                              },
                                          }
                                      }),
                                  required=False)
    time_coverage_start = forms.DateTimeField(
        initial=timezone.datetime(2000, 1, 1, tzinfo=timezone.utc))
    time_coverage_end = forms.DateTimeField(initial=timezone.now())
    source = forms.ModelMultipleChoiceField(Source.objects.all(),
                                            required=False)

    def filter(self, ds):
        """ Filtering method of the form. All filtering processes are coded here """
        # filtering based on time
        t_0 = self.cleaned_data['time_coverage_start']
        t_1 = self.cleaned_data['time_coverage_end']
        # Too early datasets are excluded from the filtering results
        ds = ds.exclude(time_coverage_end__lte=t_0)

        # Too late datasets are excluded from the filtering results
        ds = ds.exclude(time_coverage_start__gt=t_1)

        src = self.cleaned_data.get('source', None)
        # Just the one(s) with correct selected source should pass the filtering actions
        # if Source is given in the input form
        if src:
            ds = ds.filter(source__in=src)

        # spatial filtering
        if self.cleaned_data['polygon']:
            # filtering by user provided polygon
            ds = ds.filter(geographic_location__geometry__intersects=self.
                           cleaned_data['polygon'])

        # sorting
        ds = ds.order_by('time_coverage_start')
        return ds
Esempio n. 6
0
class ParkingLocationImporterForm(forms.ModelForm):
    pub_date = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%f%z'])
    geometrie = GeoJsonPointField()

    class Meta:
        model = ParkingLocation
        fields = list(constants.PARKINGLOCATION_RAW_TO_MODEL_FIELDS.values())
Esempio n. 7
0
class ViolationForm(forms.ModelForm):
    "Validate and clean Durham's violation data"

    date = forms.DateTimeField(input_formats=DATE_FORMATS)
    update_date = forms.DateTimeField(input_formats=DATE_FORMATS)

    class Meta:
        model = Violation
        fields = "__all__"

    def clean_description(self):
        # Force API sent description strings of "0" to empty string
        description = self.cleaned_data['description']
        if description == '0':
            description = ''
        return description
Esempio n. 8
0
class EstablishmentForm(forms.ModelForm):
    "Validate and clean Durham's establishment data"

    status = forms.CharField()
    lat = forms.FloatField(required=False)
    lon = forms.FloatField(required=False)
    update_date = forms.DateTimeField(input_formats=DATE_FORMATS)
    opening_date = forms.DateTimeField(input_formats=DATE_FORMATS)

    class Meta:
        model = Establishment
        exclude = ('location', 'property_id')

    def clean_city(self):
        city = self.cleaned_data['city']
        return city.title()

    def clean_status(self):
        status = self.cleaned_data['status']
        if status == 'ACTIVE':
            return 'active'
        elif status == 'DELETED':
            return 'deleted'
        raise forms.ValidationError('Invalid status')

    def clean_phone(self):
        phone = self.cleaned_data['phone']
        # Force empty phone value to empty string
        if phone == 'NULL':
            phone = ''
        return phone

    def clean(self):
        lat = self.cleaned_data.get('lat', None)
        lon = self.cleaned_data.get('lon', None)
        if lat and lon:
            self.cleaned_data['location'] = Point(lon, lat)
        return self.cleaned_data

    def save(self, commit=True):
        instance = super().save(commit=False)
        if 'location' in self.cleaned_data:
            instance.location = self.cleaned_data['location']
        instance.save()
        return instance
class SpaceTimeForm(forms.Form):
    location = PointField(
        label='Possible Contagion Site'
    )
    time = forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'],
        widget=XDSoftDateTimePickerInput(),
        label = 'Date+Time'
    )
Esempio n. 10
0
class DownloadForm(forms.ModelForm):
    choices = []
    try:
        choices = [[x.id, x] for x in Observatory.objects.all()]
    except:
        pass
    observatory_choices = forms.MultipleChoiceField(choices=choices)
    start_date = forms.DateTimeField(widget=DateInput())
    end_date = forms.DateTimeField(widget=DateInput())
    time_choices = (
        ('year', 'Year'),
        ('month', 'Month'),
        ('day', 'Day'),
        ('observation', 'Observation'),
    )
    time_frequency = forms.ChoiceField(choices=time_choices)

    class Meta(object):
        model = Observatory
        fields = []
Esempio n. 11
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
        }))
Esempio n. 12
0
class GuidanceSignImporterForm(forms.ModelForm):
    pub_date = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%f%z'])
    geometrie = GeoJsonPointField()

    def clean(self):
        '''
        The clean method normally validates unique fields here. This is overriden to
        avoid the unique validation since GuidanceSigns are updated on every import not appended to
        the table. Therefore, duplicate keys are expected.
        '''
        return self.cleaned_data

    class Meta:
        model = GuidanceSign
        fields = list(constants.GUIDANCESIGN_RAW_TO_MODEL_FIELDS.values())
Esempio n. 13
0
class InspectionForm(forms.ModelForm):
    "Validate and clean Durham's inspection data"

    score = forms.FloatField(required=False)
    date = forms.DateTimeField(input_formats=DATE_FORMATS)
    update_date = forms.DateTimeField(input_formats=DATE_FORMATS)

    class Meta:
        model = Inspection
        fields = "__all__"

    def clean_score(self):
        # Force empty score value to None so we save to DB as NULL
        score = self.cleaned_data['score']
        if not score:
            score = None
        return score

    def clean_description(self):
        # Force API sent description strings of "NULL" to empty string
        description = self.cleaned_data['description']
        if description == 'NULL':
            description = ''
        return description
Esempio n. 14
0
 def __init__(self, *args, **kwargs):
     super(FormNot, self).__init__(*args, **kwargs)
     self.fields['id_infra'].widget.attrs.update({'class': 'form-control'})
     self.fields['id_inst'].widget.attrs.update({'class': 'form-control'})
     self.fields['encabezado'].widget.attrs.update(
         {'class': 'form-control'})
     self.fields['presentacion'].widget.attrs.update(
         {'class': 'form-control'})
     self.fields['fecha_hora'] = forms.DateTimeField(
         help_text='Fecha y Hora de creación',
         widget=forms.DateTimeInput(attrs={
             'type': 'datetime-local',
             'class': 'form-control'
         }))
     self.fields['link_not'].widget.attrs.update({'class': 'form-control'})
     self.fields['arch_not'].widget.attrs.update({'class': 'form-control'})
Esempio n. 15
0
 def __init__(self, *args, **kwargs):
     categorias = GruposCategorias.objects.get(
         grupo='Documentos').idGruposCategorias.values_list('categoria')
     CHOICE_CATEGORIAS = []  # diccionario del menu
     for choice in categorias:
         CHOICE_CATEGORIAS.append((choice[0], choice[0]))
     super(FormDoc, self).__init__(*args, **kwargs)
     self.fields['id_contacto'].widget.attrs.update(
         {'class': 'form-control'})
     self.fields['categoria'] = forms.CharField(
         label='Categoria',
         required=False,
         help_text='Seleccione la categoria',
         widget=forms.Select(attrs={
             'class': "form-control",
             'placeholder': 'Categoria',
             'rows': 1
         },
                             choices=CHOICE_CATEGORIAS))
     self.fields['titulo'].widget.attrs.update({
         'class': 'form-control',
         'type': "text"
     })
     self.fields['descripcion'].widget.attrs.update({
         'class': 'form-control',
         'row': 3
     })
     self.fields['fecha_hora'] = forms.DateTimeField(
         help_text='Fecha y Hora de creación',
         widget=forms.DateTimeInput(attrs={
             'type': 'datetime-local',
             'class': 'form-control'
         }))
     self.fields['fecha_hora'].input_formats = [
         "%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M"
     ]