class ConfirmedCaseForm(forms.Form):
    estimated_date_contracted = forms.DateField(
        input_formats=['%Y-%m-%d'],
        widget=XDSoftDatePickerInput(),
        label='Estimated Date Contracted')
    date_first_symptoms = forms.DateField(input_formats=['%Y-%m-%d'],
                                          widget=XDSoftDatePickerInput(),
                                          label='Date of First Symptoms')

    date_confirmed = forms.DateField(input_formats=['%Y-%m-%d'],
                                     widget=XDSoftDatePickerInput(),
                                     label='Date Confirmed')
    additional_info = forms.CharField(widget=BootstrapTextArea(),
                                      label='Additional Information',
                                      max_length=40000,
                                      required=False)

    age_range = forms.ChoiceField(widget=BootstrapSelect(choices=age_ranges),
                                  choices=age_ranges)

    gender = forms.ChoiceField(widget=BootstrapSelect(choices=genders),
                               choices=genders)

    diseases = MultiBinaryField(
        widget=BootstrapMultiBinaryRadio(options=diseases), choices=diseases)
Ejemplo n.º 2
0
class SignupBikeanjoForm(forms.ModelForm):
    gender = forms.CharField(label=_('Gender'))
    birthday = forms.DateField(label=_('Date of birth'),
                               input_formats=["%d/%m/%Y"])
    ride_experience = forms.ChoiceField(label=_('Ride experience'),
                                        choices=models.BIKEANJO_EXPERIENCE)
    bike_use = forms.ChoiceField(label=_('Bike user'), choices=models.BIKE_USE)
    initiatives = forms.CharField(label=_('Initiatives'),
                                  required=False,
                                  max_length=256)

    class Meta:
        model = models.User
        fields = ('gender', 'birthday', 'ride_experience', 'bike_use',
                  'initiatives')
Ejemplo n.º 3
0
 def __init__(self, user, *args, **kwargs):
     super(AssignmentForm, self).__init__(*args, **kwargs)
     if user.profile.temp_address:
         address = user.profile.temp_address
     else:
         address = user.profile.address
     g = geocoder.mapbox(address, key=MB_KEY)
     p = Point(g.latlng[0], g.latlng[0], srid=4326)
     supply = Supply.objects.annotate(
         distance=Distance('location', p)).order_by('distance')[0:]
     stock = DrugStock.objects.annotate(
         distance=Distance('location', p)).order_by('distance')[0:]
     su = [(q.id, q.address) for q in supply]
     st = [(q.id, q.address) for q in stock]
     self.fields['pick_point'] = forms.ChoiceField(choices=su)
     self.fields['drop_point'] = forms.ChoiceField(choices=st)
Ejemplo n.º 4
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
Ejemplo n.º 5
0
class FeatureLinkForm(forms.ModelForm):

    feature_to = forms.ChoiceField(label='Signalement lié')

    class Meta:
        model = FeatureLink
        fields = (
            'relation_type',
            'feature_to',
        )

    def __init__(self, *args, **kwargs):
        feature_type = kwargs.pop('feature_type', None)
        feature = kwargs.pop('feature', None)
        super().__init__(*args, **kwargs)

        try:
            qs = Feature.objects.filter(feature_type=feature_type)
            if feature:
                qs = qs.exclude(feature_id=feature.feature_id)

            self.fields['feature_to'].choices = tuple(
                (feat.feature_id, "{} ({} - {})".format(
                    feat.title, feat.creator.display_creator,
                    feat.created_on.strftime("%d/%m/%Y %H:%M")))
                for feat in qs)

        except Exception:
            logger.exception('No feature_type found')
Ejemplo n.º 6
0
class NewProjectionPhotoForm(forms.Form):
    # projection type
    front_view_photo = "FRT"
    side_first_view_photo = "SD1"
    side_second_view_photo = "SD2"
    back_view_photo = "BCK"

    projection_view_type = forms.ChoiceField(label=_('Выберите вид к которому относится фото'),
                                             widget = forms.Select(attrs = {'class': 'form-control'}),
                                             choices = (
                                                        (front_view_photo, _('Передний вид')),
                                                        (side_first_view_photo, _('Боковой вид №1')),
                                                        (side_second_view_photo, _('Боковой вид №2')),
                                                        (back_view_photo, _('Задний вид')),
                                                        )
                                            )
    # фото проекции
    projection_view_photo = forms.ImageField(label=_("Выберите изображение"),
                                             widget = forms.ClearableFileInput(attrs = {'class': 'form-control',
                                                                                        'type':'file'}))

    projection_view_description = forms.CharField(label=_('Описание'), max_length=100, required=False,
                                                  widget = forms.Textarea(attrs = {'class': 'form-control',
                                                                                    'rows': "5" 
                                                                                  }
                                                                         )
                                                 )
Ejemplo n.º 7
0
class SupplierContactForm(forms.ModelForm):
    required_css_class = 'required'
    error_css_class = 'error'

    company = forms.CharField(
        widget=forms.TextInput(attrs={
            'placeholder': 'Your company',
            'class': 'input-lg'
        }), )
    email = forms.EmailField(
        widget=forms.TextInput(attrs={
            'placeholder': 'Email address',
            'class': 'input-lg'
        }), )
    phone = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': 'Phone number',
        'class': 'input-lg'
    }),
                            required=False)
    website = forms.CharField(
        widget=forms.TextInput(attrs={
            'placeholder': 'www.your-company.com',
            'class': 'input-lg'
        }),
        required=False)
    type_of_business = forms.ChoiceField(
        label='',
        choices=SupplierContact.SUPPLIER_TYPE_CHOICES,
        widget=forms.RadioSelect(),
        help_text=_('Please select your type of business.'))

    class Meta:
        exclude = []
        model = SupplierContact
Ejemplo n.º 8
0
    def __init__(self, *args, **kwargs):
        feature_type = kwargs.pop('feature_type')
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        project = feature_type.project

        # Status choices
        initial = 'draft'
        choices = tuple(x for x in Feature.STATUS_CHOICES)
        if not project.moderation:
            choices = tuple(x for x in Feature.STATUS_CHOICES if x[0] != 'pending')
            initial = 'published' if not self.instance else self.instance.status

        if project.moderation and not Authorization.has_permission(user, 'can_publish_feature', project):
            choices = tuple(x for x in Feature.STATUS_CHOICES if x[0] in ['draft', 'pending'])
            initial = 'pending'

        if project.moderation and Authorization.has_permission(user, 'can_publish_feature', project):
            choices = tuple(x for x in Feature.STATUS_CHOICES if x[0] in ['draft', 'published', 'archived'])
            initial = 'draft'

        self.fields['status'] = forms.ChoiceField(
            choices=choices,
            initial=initial,
            label='Statut'
        )
Ejemplo n.º 9
0
class RequesterUserInforForm(forms.ModelForm):
    birthday = forms.DateField(label=_('Date of birth'),
                               input_formats=["%d/%m/%Y"])
    ride_experience = forms.ChoiceField(label=_('Ride experience'),
                                        choices=models.REQUESTER_EXPERIENCE)

    class Meta:
        fields = (
            'avatar',
            'first_name',
            'last_name',
            'email',
            'language',
            'country',
            'city_alias',
            'gender',
            'birthday',
            'ride_experience',
        )
        model = models.User

    def save(self, **kwargs):
        city_alias = self.cleaned_data.get('city_alias')
        if city_alias:
            self.instance.city = city_alias.city
        super(RequesterUserInforForm, self).save(**kwargs)
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
class LabNetworkForm(FormCleanMixin):
    operational_since = forms.ChoiceField(
        choices=hospital_operational_since_choices, required=False)
    about = forms.CharField(widget=forms.Textarea, required=False)

    class Meta:
        model = LabNetwork
        exclude = ()
        widgets = {
            'matrix_state':
            autocomplete.ModelSelect2(url='matrix-state-autocomplete'),
            'matrix_city':
            autocomplete.ModelSelect2(url='matrix-city-autocomplete',
                                      forward=['matrix_state'])
        }

    def validate_qc(self):
        qc_required = {
            'name': 'req',
            'operational_since': 'req',
            'about': 'req',
            'network_size': 'req',
            'building': 'req',
            'locality': 'req',
            'matrix_city': 'req',
            'matrix_state': 'req',
            'country': 'req',
            'pin_code': 'req',
            'labnetworkmanager': 'count',
            'labnetworkhelpline': 'count',
            'labnetworkemail': 'count'
        }

        # if self.instance.is_billing_enabled:
        #     qc_required.update({
        #         'lab_documents': 'count'
        #     })

        for key, value in qc_required.items():
            if value == 'req' and not self.cleaned_data[key]:
                raise forms.ValidationError(key +
                                            " is required for Quality Check")
            if self.data.get(key +
                             '_set-TOTAL_FORMS') and value == 'count' and int(
                                 self.data[key + '_set-TOTAL_FORMS']) <= 0:
                raise forms.ValidationError("Atleast one entry of " + key +
                                            " is required for Quality Check")
            if self.data.get(key +
                             '-TOTAL_FORMS') and value == 'count' and int(
                                 self.data.get(key + '-TOTAL_FORMS')) <= 0:
                raise forms.ValidationError("Atleast one entry of " + key +
                                            " is required for Quality Check")

    def clean_operational_since(self):
        data = self.cleaned_data['operational_since']
        if data == '':
            return None
        return data
Ejemplo n.º 12
0
class SignupRequesterForm(forms.ModelForm):
    gender = forms.CharField(label=_('Gender'))
    birthday = forms.DateField(label=_('Date of birth'),
                               input_formats=["%d/%m/%Y"])
    ride_experience = forms.ChoiceField(choices=models.REQUESTER_EXPERIENCE)

    class Meta:
        model = models.User
        fields = ('gender', 'birthday', 'ride_experience')
Ejemplo n.º 13
0
class ShopForm(forms.ModelForm):
    name = forms.CharField(max_length=100, help_text="Please enter your Company name")
    location = forms.PointField(help_text="Please pin your company's location on the map")
    address = forms.CharField(max_length=150, help_text="Please enter your company's address")
    city = forms.CharField(max_length=50, help_text="Please input your City")
    urge = forms.ChoiceField(choices=URGENCY, help_text="Please state how urgent the food is!")
    
    class Meta:
        model = Shop
        fields = ('name','location','address','city','urge')
Ejemplo n.º 14
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
Ejemplo n.º 15
0
class ImporterForm(forms.ModelForm):
    timezone = forms.ChoiceField(choices=[(
        "US/Eastern",
        "Eastern"), ("US/Central",
                     "Central"), ("US/Mountain",
                                  "Mountain"), ("US/Pacific", "Pacific")])

    class Meta:
        exclude = ["last_run"]
        model = Importer
class ContagionSiteForm(forms.Form):
    location = PointField(label='Possible Contagion Site')
    start_date = forms.DateField(input_formats=['%Y-%m-%d'],
                                 widget=XDSoftDatePickerInput(),
                                 label='START')
    end_date = forms.DateField(input_formats=['%Y-%m-%d'],
                               widget=XDSoftDatePickerInput(),
                               label='END')
    radius = forms.ChoiceField(widget=BootstrapSelect(choices=radii),
                               choices=radii)
Ejemplo n.º 17
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)
Ejemplo n.º 18
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')
Ejemplo n.º 19
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',
        ]
Ejemplo n.º 20
0
class NewParameterData(forms.Form):
    # gym user name
    user_parameter = forms.ChoiceField(label=_('Выберите параметр'),
                                       widget = forms.Select(attrs = {'class': 'main-inp wide'}),
                                       choices = [])
    # gym user description
    body_data = ''

    def __init__(self, *args, **kwargs):
        super(NewParameterData, self).__init__(*args, **kwargs)
        user_id = kwargs.pop('user_id', None)
        # получаем список всех параметров выбранного пользователя
        all_user_params = BodyParameter.objects.filter(user__user__id=user_id)
        self.fields['user_parameter'].choices = ((x.id, x.body_title) for x in all_user_params)
Ejemplo n.º 21
0
class FeatureSelectFieldAdminForm(forms.Form):
    related_field = forms.ChoiceField(
        label="Champs à ajouter",
        choices=[(str(field.name),
                  "{0} - {1}".format(field.name, field.get_internal_type()))
                 for field in Feature._meta.get_fields()],
        required=False)
    alias = forms.CharField(
        label="Alias",
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': "Alias pour cette colonne"
        }))
Ejemplo n.º 22
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',
        )
Ejemplo n.º 23
0
class CompanyForm(forms.Form):
    name = forms.CharField(max_length=200, label='Company name')
    logo = forms.ImageField(label='Logo')
    description = forms.CharField(widget=forms.Textarea)
    location = forms.PointField(widget=forms.OSMWidget(attrs={'map_width': 700, 'map_height': 500}))
    category = forms.ChoiceField(choices=categories) # TODO put list
    help_message = forms.CharField(widget=forms.Textarea, label='How can I get help') # blank=True
    opening_hours = forms.CharField() # max_length=400, blank=True

    cover = forms.ImageField(label='Cover picture')

    other_image1 = forms.ImageField(label='Other image # 1', required=False)
    other_image2 = forms.ImageField(label='Other image # 2', required=False)
    other_image3 = forms.ImageField(label='Other image # 3', required=False)
    
    # services
    service1_cat = forms.ChoiceField(choices=service_categories, label='Service # 1 category')
    service1_desc = forms.CharField(widget=forms.Textarea, label='Service # 1 description', required=False)

    service2_cat = forms.ChoiceField(choices=service_categories, label='Service # 2 category')
    service2_desc = forms.CharField(widget=forms.Textarea, label='Service # 2 description', required=False)

    service3_cat = forms.ChoiceField(choices=service_categories, label='Service # 3 category')
    service3_desc = forms.CharField(widget=forms.Textarea, label='Service # 3 description', required=False)
Ejemplo n.º 24
0
    def __init__(self, *args, **kwargs):
        feature_type = kwargs.pop('feature_type')
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        project = feature_type.project

        # Status choices
        initial = 'draft'
        choices = tuple(x for x in Feature.STATUS_CHOICES)
        if not project.moderation:
            choices = tuple(x for x in Feature.STATUS_CHOICES
                            if x[0] != 'pending')
            initial = 'published' if not self.instance else self.instance.status

        if project.moderation and not Authorization.has_permission(
                user, 'can_publish_feature', project):
            choices = tuple(x for x in Feature.STATUS_CHOICES
                            if x[0] in ['draft', 'pending'])
            initial = 'pending'

        if project.moderation and Authorization.has_permission(
                user, 'can_publish_feature', project):
            choices = tuple(x for x in Feature.STATUS_CHOICES
                            if x[0] in ['draft', 'published', 'archived'])
            initial = 'draft'

        self.fields['status'] = forms.ChoiceField(choices=choices,
                                                  initial=initial,
                                                  label='Statut')

        # TODO: factoriser les attributs de champs geom
        if feature_type.geom_type == "point":
            self.fields['geom'] = forms.PointField(label="Localisation",
                                                   required=True,
                                                   srid=4326)

        if feature_type.geom_type == "linestring":
            self.fields['geom'] = forms.LineStringField(label="Localisation",
                                                        required=True,
                                                        srid=4326)

        if feature_type.geom_type == "polygon":
            self.fields['geom'] = forms.PolygonField(label="Localisation",
                                                     required=True,
                                                     srid=4326)
Ejemplo n.º 25
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
Ejemplo n.º 26
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 = []
Ejemplo n.º 27
0
class DownloadDataForm(forms.Form):
    DATA_NAMES = [
        ('Kidney_Sample_Annotations.txt', 'Kidney_Sample_Annotations.txt'),
        ('Kidney_Feature_Annotations.txt', 'Kidney_Feature_Annotations.txt'),
        ('Kidney_Raw_BioProbeCountMatrix.txt',
         'Kidney_Raw_BioProbeCountMatrix.txt'),
        ('Kidney_Raw_TargetCountMatrix.txt',
         'Kidney_Raw_TargetCountMatrix.txt'),
        ('Kidney_Q3Norm_TargetCountMatrix.txt',
         'Kidney_Q3Norm_TargetCountMatrix.txt'),
        ('Cell_Types_for_Spatial_Decon.txt',
         'Cell_Types_for_Spatial_Decon.txt'),
        ('Young_kidney_cell_profile_matrix.csv',
         'Young_kidney_cell_profile_matrix.csv'),
        ('Kidney_ssGSEA.txt', 'Kidney_ssGSEA.txt'),
    ]

    data_name = forms.ChoiceField(
        label='Name of txt/csv file to download',
        required=False,
        choices=DATA_NAMES,
        widget=forms.Select(attrs={'class': 'form-control mr-sm-1'}))
Ejemplo n.º 28
0
 def __init__(self, *args, **kwargs):
     super(BandInlineForm, self).__init__(*args, **kwargs)
     self.fields['data_type'] = forms.ChoiceField(
         choices=get_gdal_data_type_choices())
     self.fields['color_interpretation'] = forms.ChoiceField(
         choices=get_gdal_color_interpretation_choices())
Ejemplo n.º 29
0
class EmpleadoForm(forms.Form):

    cedula = forms.CharField(required=False, label=u'Cédula')
    nombres = forms.CharField(max_length=250,
                              widget=forms.TextInput(attrs={'size': '30'}))
    apellido_paterno = forms.CharField(
        max_length=250, widget=forms.TextInput(attrs={'size': '30'}))
    apellido_materno = forms.CharField(
        max_length=250,
        widget=forms.TextInput(attrs={'size': '30'}),
        required=False)

    pais = forms.ModelChoiceField(
        queryset=Pais.objects.all(),
        empty_label="Escoger un pais",
        widget=forms.Select(attrs={
            'placeholder': 'País',
            'onChange': "getProvincias(this.value)"
        }))
    provincia = forms.ModelChoiceField(
        queryset=Provincia.objects.none(),
        empty_label="Escoger una provincia",
        widget=forms.Select(
            attrs={
                'placeholder': 'Provincia o estado',
                'onChange': "getCiudades(this.value)"
            }))
    ciudad = forms.ModelChoiceField(
        queryset=Ciudad.objects.none(),
        empty_label="Escoger una ciudad",
        widget=forms.Select(attrs={'placeholder': 'Ciudad o Cantón'}))

    sexo = forms.ChoiceField(choices=PersonaNatural.SEXO_CHOICES,
                             required=True)
    fecha_nacimiento = forms.DateField(required=False)
    observaciones = forms.CharField(widget=forms.Textarea())
    usuario = forms.CharField(max_length=13,
                              widget=forms.TextInput(attrs={'size': '30'}))
    contrasenia = forms.CharField(
        max_length=13, widget=forms.PasswordInput(attrs={'size': '30'}))
    email = forms.EmailField(max_length=25,
                             widget=forms.TextInput(attrs={'size': '30'}))
    plazas_trabajo = forms.ModelMultipleChoiceField(
        queryset=PlazaTrabajo.objects.all(), widget=forms.SelectMultiple)
    foto = forms.ImageField(required=False)

    def modificarQuerySet(self, pais_id, provincia_id):
        if pais_id not in ('', None):
            self.fields['provincia'].queryset = Provincia.objects.filter(
                pais__id=pais_id)

        if provincia_id not in ('', None):
            self.fields['ciudad'].queryset = Ciudad.objects.filter(
                provincia__id=provincia_id)

    def save(self, empleado=None):
        cleaned_data = super(EmpleadoForm, self).clean()

        if empleado is None:
            persona = Persona()
            persona.tipo = Persona.TIPO_PERSONA_NATURAL
            persona.observaciones = cleaned_data["observaciones"]
            persona.ruc = cleaned_data["cedula"]
            persona.nombre_comercial = ""
            persona.save()

            usuario = User()
            usuario.username = cleaned_data["usuario"]
            usuario.set_password(cleaned_data["contrasenia"])
            usuario.email = cleaned_data["email"]
            usuario.save()

            persona_natural = PersonaNatural()
            persona_natural.ciudad_nacimiento = cleaned_data['ciudad']
            persona_natural.cedula = cleaned_data["cedula"]
            persona_natural.nombres = cleaned_data["nombres"]
            persona_natural.apellido_paterno = cleaned_data["apellido_paterno"]
            persona_natural.apellido_materno = cleaned_data["apellido_materno"]
            persona_natural.persona = persona
            persona_natural.sexo = cleaned_data["sexo"]
            persona_natural.fecha_nacimiento = cleaned_data["fecha_nacimiento"]
            persona_natural.save()

            empleado = Empleado()
            empleado.persona = persona_natural
            empleado.usuario = usuario
            empleado.foto = cleaned_data["foto"]
            empleado.observaciones = cleaned_data["observaciones"]
            empleado.save()
            empleado.plazas_trabajo = cleaned_data["plazas_trabajo"]
            empleado.save()
        else:
            empleado.persona.nombres = cleaned_data["nombres"]
            empleado.persona.apellido_paterno = cleaned_data[
                "apellido_paterno"]
            empleado.persona.apellido_materno = cleaned_data[
                "apellido_materno"]
            empleado.persona.sexo = cleaned_data["sexo"]
            empleado.persona.cedula = cleaned_data["cedula"]
            empleado.persona.ciudad_nacimiento = cleaned_data["ciudad"]
            empleado.persona.save()

            empleado.usuario.email = cleaned_data["email"]
            empleado.usuario.save()

            empleado.foto = cleaned_data["foto"]
            empleado.observaciones = cleaned_data["observaciones"]
            empleado.save()

            empleado.plazas_trabajo = cleaned_data["plazas_trabajo"]
            empleado.save()

        return empleado

    def clean_usuario(self):
        if self.cleaned_data['usuario']:
            p = User.objects.filter(username=self.cleaned_data['usuario'])
            if len(p) > 0:
                raise forms.ValidationError(
                    _("Ya esxiste un usuario con este username"))
        return self.cleaned_data['usuario']
Ejemplo n.º 30
0
 def __init__(self, *args, **kwargs):
     super(NilValueSetForm, self).__init__(*args, **kwargs)
     self.fields['data_type'] = forms.ChoiceField(
         choices=get_gdal_data_type_choices())