class Meta: model = Diarrhea_Symptom exclude = ['symptom'] widgets = { 'vomit': CheckboxInput(attrs={'class': 'form-check-input'}), 'flux_stool': CheckboxInput(attrs={'class': 'form-check-input'}), 'fever': CheckboxInput(attrs={'class': 'form-check-input'}), 'diarrhea_amount': NumberInput(attrs={'class': 'form-control'}), 'diarrhea_detail': TextInput(attrs={'class': 'form-control'}), 'stomachache': TextInput(attrs={'class': 'form-control'}), 'bowel_sound': TextInput(attrs={'class': 'form-control'}), 'current_history': Textarea(attrs={'class': 'form-control','rows':"15", 'cols':"4"}) }
class KappaForm(forms.Form): user_1 = forms.ModelChoiceField(queryset=User.objects.all()) user_2 = forms.ModelChoiceField(queryset=User.objects.all()) percent = forms.FloatField(widget=NumberInput( attrs={ 'id': 'percent', 'value': '10', 'min': '0', 'max': '100', 'step': '0.5' })) number = forms.IntegerField(widget=NumberInput(attrs={ 'id': 'number', 'value': '10', 'min': '0' })) intervention = TreeNodeChoiceField( queryset=Intervention.objects.all().get_descendants(include_self=True), level_indicator="---") outcome = TreeNodeChoiceField( queryset=Outcome.objects.all().get_descendants(include_self=True), level_indicator="---")
class ServicioAdministradorFilter(django_filters.FilterSet): id = django_filters.NumberFilter(field_name='id', lookup_expr='iexact', widget=NumberInput(attrs={'min': 1})) estado =django_filters.ChoiceFilter(choices=ESTADO_SERVICIO,field_name="estado", label="Estado") fecha = django_filters.DateFilter(field_name="solicitudServicio__fecha", label="Fecha", widget=TextInput(attrs={'placeholder': 'dd/mm/yyyy'})) plaga = django_filters.ModelChoiceFilter(queryset=Plaga.objects.all(), field_name="solicitudServicio__plaga", label="Plaga") trabajador = django_filters.ModelChoiceFilter(queryset=Trabajador.objects.all(), field_name="trabajador", label="Trabajador") class Meta: model = Servicio fields = ["trabajador"] exclude=['trabajador']
class Meta: model = Query fields = ("category", "make", "country", "manufacturer", "manufacturerYear", "city", "zipCode", "usedDuration") widgets = { # 'visualQualityRating': NumberInput (attrs={'type': 'range', 'step': '1', 'max': '10', 'min': '1', # 'value': '5', 'oninput': 'visualOutput.value=this.value'}), 'manufacturerYear': NumberInput( attrs={ 'type': 'range', 'step': '1', 'max': '10', 'min': '1', 'value': '5', 'oninput': 'yearOutput.value=this.value' }), 'zipCode': NumberInput( attrs={ 'type': 'range', 'step': '1', 'max': '10', 'min': '1', 'value': '5', 'oninput': 'zipOutput.value=this.value' }), 'usedDuration': NumberInput( attrs={ 'type': 'range', 'step': '1', 'max': '10', 'min': '1', 'value': '5', 'oninput': 'usedDOutput.value=this.value' }), }
class Meta: model = RapidInventory fields = [ 'dominating_specie', 'flowers', 'dead_trees_on_ground', 'dead_trees_on_root', 'fire_marks', 'lumberjack_marks', 'machete_marks', 'invasive_species', 'stag_marks', 'pig_marks', 'electric_ant_marks', 'other_observations' ] widgets = { 'dead_trees_on_ground': NumberInput(attrs={ 'min': '0', }), }
class Meta: model = AlbumItem widgets = { "image": FileInputButtonBase, "order": NumberInput(attrs={"style": "width: 80px !important;"}), } fields = [ "album", "title", "order", "image", ] exclude = []
class Meta: model = Rash_Symptom exclude = ['symptom'] widgets = { 'rash_area': TextInput(attrs={'class': 'form-control'}), 'rash_date': NumberInput(attrs={'class': 'form-control'}), 'itch': CheckboxInput(attrs={'class': 'form-check-input'}), 'pain': CheckboxInput(attrs={'class': 'form-check-input'}), 'sting': CheckboxInput(attrs={'class': 'form-check-input'}), 'fever': CheckboxInput(attrs={'class': 'form-check-input'}), 'swell': CheckboxInput(attrs={'class': 'form-check-input'}), 'rash_detail': TextInput(attrs={'class': 'form-control'}), 'pe': Textarea(attrs={'class': 'form-control', 'rows':'6', 'cols': '4'}), }
def __init__(self, max_value='12', min_value='1', default_value='12', **kwargs): self.field = forms.IntegerField(widget=NumberInput( attrs={ 'type': 'range', 'step': '1', 'max': max_value, 'min': min_value, 'value': default_value })) super().__init__(**kwargs)
class FormCrearObservacion(forms.ModelForm): class Meta: model = HistorialObservacion fields = ['fecha', 'observacion'] fecha = forms.DateField( initial=datetime.date.today, widget=NumberInput(attrs={ 'autofocus': 'autofocus', 'type': 'date', 'class': 'form-control' })) observacion = forms.CharField(widget=forms.Textarea( attrs={'class': 'form-control'}))
def __init__(self, attrs=None): freqOptions = [(DAILY, _("Daily")), (WEEKLY, _("Weekly")), (MONTHLY, _("Monthly")), (YEARLY, _("Yearly"))] ordOptions1 = [(1, toTheOrdinal(1)), (2, toTheOrdinal(2)), (3, toTheOrdinal(3)), (4, toTheOrdinal(4)), (5, toTheOrdinal(5)), (-1, toTheOrdinal(-1)), (EVERY_DAY, _("Every")), (SAME_DAY, _("The Same"))] ordOptions2 = [(None, ""), (1, toTheOrdinal(1)), (2, toTheOrdinal(2)), (3, toTheOrdinal(3)), (4, toTheOrdinal(4)), (5, toTheOrdinal(5)), (-1, toTheOrdinal(-1))] dayOptions1 = enumerate(WEEKDAY_ABBRS) dayOptions2 = [(None, "")] + list(enumerate(WEEKDAY_NAMES)) dayOptions3 = list(enumerate(WEEKDAY_NAMES)) +\ [(DAY_OF_MONTH, _("Day of the month"))] monthOptions = enumerate(MONTH_ABBRS[1:], 1) numAttrs = {'min': 1, 'max': 366} disableAttrs = {'disabled': True} if attrs: numAttrs.update(attrs) disableAttrs.update(attrs) widgets = [ AdminDateInput(attrs=attrs), Select(attrs=attrs, choices=freqOptions), #1 NumberInput(attrs=numAttrs), CheckboxSelectMultiple(attrs=attrs, choices=dayOptions1), NumberInput(attrs=numAttrs), AdminDateInput(attrs=attrs), #5 Select(attrs=attrs, choices=ordOptions1), Select(attrs=attrs, choices=dayOptions3), Select(attrs=disableAttrs, choices=ordOptions2), Select(attrs=disableAttrs, choices=dayOptions2), Select(attrs=disableAttrs, choices=ordOptions2), #10 Select(attrs=disableAttrs, choices=dayOptions2), CheckboxSelectMultiple(attrs=attrs, choices=monthOptions) ] super().__init__(widgets, attrs)
def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') location_type = kwargs.pop('location_type') super(LocationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-LocationForm' self.helper.form_class = 'trip_forms' self.helper.form_method = 'post' self.helper.form_action = '' self.fields['title'].label = 'Title for Trip Plan' self.fields['date'].label = 'Date' self.fields['date'] = forms.ChoiceField(choices=choices) self.fields['latitude'].widget = NumberInput(attrs={ 'step': 'any', 'max': 90, 'min': -90 }) self.fields['longitude'].widget = NumberInput(attrs={ 'step': 'any', 'max': 180, 'min': -180 }) self.helper.layout = Layout( 'title', Div('latitude', 'longitude', css_class='coordinate-fields'), 'date', Field('trip', type='hidden'), Field('location_type', type='hidden'), FormActions( Submit('submit', '{{ submit_button_title }}', css_class='btn btn-success btn-lg click-disable'), HTML( '<a class="btn btn-secondary" href="{% url cancel_button_path trip_id %}" name="cancel">Cancel</a>' ))) if location_type == TripLocation.BEGIN: self.helper['date'].wrap(Field, type='hidden')
class MembraneTopolForm(ModelForm): name = forms.CharField(label='Name', widget=TextInput(attrs={'class': 'form-control'})) forcefield = forms.ModelChoiceField(queryset=Forcefield.objects.all()) temperature = forms.IntegerField(label='Temperature (°K)', widget=NumberInput(attrs={'class': 'form-control'})) equilibration = forms.IntegerField(label='Equilibration (ns)', widget=NumberInput(attrs={'class': 'form-control'})) mem_file = forms.FileField(label='Membrane file', required=False) other_file = forms.FileField(label='Parameters files', required=False) description = forms.CharField(widget=Textarea(attrs={'class': 'form-control'}), required=False) class Meta: model = MembraneTopol fields = ['name', 'software', 'forcefield', 'temperature', 'equilibration', 'mem_file', 'other_file', 'doi', 'description', 'prot', 'reference'] widgets = {'reference': autocomplete.ModelSelect2Multiple(url='reference-autocomplete'), 'software': autocomplete.ModelSelect2(url='software-autocomplete'), 'prot': autocomplete.ModelSelect2Multiple(url='membraneprotautocomplete', attrs={'data-placeholder': 'e.g., GPRC'}), 'doi': autocomplete.ModelSelect2Multiple(url='membranedoiautocomplete', attrs={'data-placeholder': 'e.g., 10.5281/zenodo.4424934'}), 'forcefield': Select(attrs={'class': 'form-control'})} labels = {'reference': 'References', 'prot': 'Proteins', 'doi': 'Zenodo DOI'} def clean(self): 'Validation of the zenodo doi field' cleaned_data = super(MembraneTopolForm, self).clean() dois = cleaned_data.get('doi') for doi in dois: lm_response = requests.get('http://doi.org/%s' % doi.doi) if lm_response.status_code != 200: self.add_error('doi', mark_safe('%s is an invalid DOI for Zenodo' % doi))
def __init__(self, attrs=None): freqOptions = [(3, "Daily"), (2, "Weekly"), (1, "Monthly"), (0, "Yearly")] ordOptions1 = [(1, "The First"), (2, "The Second"), (3, "The Third"), (4, "The Fourth"), (5, "The Fifth"), (-1, "The Last"), (_EveryDay, "Every"), (_SameDay, "The Same")] ordOptions2 = [(None, ""), (1, "The First"), (2, "The Second"), (3, "The Third"), (4, "The Fourth"), (5, "The Fifth"), (-1, "The Last")] dayOptions1 = enumerate(calendar.day_abbr) dayOptions2 = [(None, "")] + list(enumerate(calendar.day_name)) dayOptions3 = list(enumerate(calendar.day_name)) +\ [(_DayOfMonth, "Day of the month")] monthOptions = enumerate(calendar.month_abbr[1:], 1) numAttrs = {'min': 1, 'max': 366} disableAttrs = {'disabled': True} if attrs: numAttrs.update(attrs) disableAttrs.update(attrs) widgets = [ AdminDateInput(attrs=attrs), Select(attrs=attrs, choices=freqOptions), #1 NumberInput(attrs=numAttrs), CheckboxSelectMultiple(attrs=attrs, choices=dayOptions1), NumberInput(attrs=numAttrs), AdminDateInput(attrs=attrs), #5 Select(attrs=attrs, choices=ordOptions1), Select(attrs=attrs, choices=dayOptions3), Select(attrs=disableAttrs, choices=ordOptions2), Select(attrs=disableAttrs, choices=dayOptions2), Select(attrs=disableAttrs, choices=ordOptions2), #10 Select(attrs=disableAttrs, choices=dayOptions2), CheckboxSelectMultiple(attrs=attrs, choices=monthOptions) ] super().__init__(widgets, attrs)
def get_form(self, form_class=None): # form.fields['proteins'].widget = NumberInput(attrs={'type':'range', 'step': '5'}) form = super().get_form(form_class) range_fields = ['proteins', 'carbs', 'fats'] for field in form.fields: if field in range_fields: form.fields[field].widget = NumberInput(attrs={ 'type': 'range', 'class': 'custom-range', 'step': '5' }) else: form.fields[field].widget.attrs.update( {'class': 'form-control'}) return form
class Meta: model = Issue fields = [ 'title', 'kanbancol', 'due_date', 'type', 'assignee', 'priority', 'description', 'storypoints', 'dependsOn', 'tags' ] widgets = { # Use localization and bootstrap 3 'due_date': DateWidget(attrs={'id': "due_date"}, usel10n=True, bootstrap_version=3), 'storypoints': NumberInput(attrs={'min': 0}) }
class ControlPanelForm(forms.ModelForm): threshold = forms.FloatField(required=True, min_value=-1.0, max_value=1.0, widget=NumberInput(attrs={'step': "0.01"})) def clean(self): cp = self.cleaned_data if cp.get('threshold') is None: self.add_error('threshold', "Cannot be empty") return cp class Meta: model = ControlPanel fields = ['threshold']
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Rate')) for field in self.fields: self.fields[field].widget = NumberInput( attrs={ 'type': 'range', 'list': 'range', 'step': '2', 'class': 'custom-range', 'min': '1', 'max': '100' })
class MenuItemForm(ModelForm): category = ModelChoiceField(queryset=MenuCategory.objects.filter( deleted=False)) class Meta: model = MenuItem fields = ['name', 'category', 'price'] name = forms.CharField(widget=TextInput(attrs={ 'class': 'validate', 'placeholder': 'Name' })) price = forms.DecimalField(widget=NumberInput(attrs={ 'class': 'validate', 'placeholder': 9.99 }))
def __init__(self, *args, **kwargs): super(RatingForm, self).__init__(*args, **kwargs) self.fields['beer_name'].widget = TextInput(attrs={ 'placeholder': 'Cider Name', 'required': 'true' }) self.fields['brewer_name'].widget = TextInput( attrs={'placeholder': 'Brewer Name'}) self.fields['notes'].widget = TextInput(attrs={'placeholder': 'Notes'}) self.fields['score'].widget = NumberInput(attrs={ 'min': 1, 'max': 10, 'required': 'true' })
class UserProfileForm(forms.ModelForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phoneNumber = forms.CharField(validators=[phone_regex], max_length=17, widget=forms.NumberInput( attrs={'class': 'form-control', 'placeholder': '+237 678248748'})) dob = forms.DateField(widget=NumberInput(attrs={'class': 'form-control', 'type': 'date'}), required=True) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' class Meta(): model = UserProfile fields = ('dob', 'phoneNumber', 'country', 'profileImage') widgets = {'country': CountrySelectWidget()}
class LeakFormThree(forms.Form): DescribeRepair = forms.CharField(widget=forms.Textarea) RepairDate = forms.DateField(widget=NumberInput(attrs={'type': 'date'})) MeterNum = forms.DecimalField() MeterReading = forms.DecimalField() PipeLeak = forms.BooleanField(required=False) ValveLeak = forms.BooleanField(required=False) FittingLeak = forms.BooleanField(required=False) ToiletLeak = forms.BooleanField(required=False) OtherLeak = forms.BooleanField(required=False) ddlTypeOfPipe = forms.ChoiceField( choices=[('lead', 'Lead'), ('copper', 'Copper'), ('plastic', 'Plastic'), ('other', 'Other')]) Explain = forms.CharField(widget=forms.Textarea)
class Meta: model = Allocation fields = ['securities', 'desired_pct'] labels = { 'securities': 'Select one or several securities.', 'desired_pct': 'The percentage of your portfolio to allocate to this group of securities: ' } widgets = { 'desired_pct': NumberInput(attrs={ 'min': 0, 'max': 100, 'width': 50 }), 'securities': CheckboxSelectMultiple }
class Meta: model = Listing fields = ['name', 'description', 'price', 'picture', 'category'] widgets = { 'name': TextInput(attrs={'placeholder': 'Your listing name'}), 'description': Textarea(attrs={'placeholder': 'Short description of your item'}), 'price': NumberInput(attrs={ 'min': '0.01', 'step': 'any', 'placeholder': '€' }), 'category': CheckboxSelectMultiple() }
def _customize_widgets(form): for field_name in form.fields: if form.mutate_date_input and issubclass(form.fields[field_name].widget.__class__, DateInput): form.fields[field_name].widget = NumberInput( attrs={"type": "date"}) if form.number_input_for_date else SelectDateWidget() if form.mutate_inputs and issubclass(form.fields[field_name].widget.__class__, SelectDateWidget): _update_select_class(form.fields[field_name].widget.attrs) elif form.mutate_inputs and issubclass(form.fields[field_name].widget.__class__, NumberInput): _update_input_class(form.fields[field_name].widget.attrs) elif form.mutate_text_area and issubclass(form.fields[field_name].widget.__class__, Textarea): _update_input_class(form.fields[field_name].widget.attrs) elif form.mutate_inputs and issubclass(form.fields[field_name].widget.__class__, Input): _update_input_class(form.fields[field_name].widget.attrs) elif issubclass(form.fields[field_name].widget.__class__, Select) and form.mutate_select and not isinstance(form.fields[field_name].widget, SelectMultiple): _update_select_class(form.fields[field_name].widget.attrs) elif form.mutate_select_multiple and isinstance(form.fields[field_name].widget, SelectMultiple): _update_select_class(form.fields[field_name].widget.attrs)
def render(self, name, value, attrs=None, renderer=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, (str, bytes)): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name # Day input local_attrs = self.build_attrs({'id': self.day_field % id_}) s = NumberInput(attrs={'class': 'form-control', 'placeholder': 'Day'}) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(self.sqeeze_form_group(select_html)) # Month input if hasattr(self, 'month_choices'): local_attrs = self.build_attrs({'id': self.month_field % id_}) s = Select(choices=self.month_choices, attrs={'class': 'form-control'}) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(self.sqeeze_form_group(select_html)) # Year input local_attrs = self.build_attrs({'id': self.year_field % id_}) s = NumberInput(attrs={'class': 'form-control', 'placeholder': 'Year'}) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(self.sqeeze_form_group(select_html)) output = '<div class="row mb-0">{0}</div>'.format(u'\n'.join(output)) return mark_safe(output)
class Meta: model = Post is_multipart = True fields = ('name', 'photo', 'user_score', 'info', 'rubric', 'show_authorship') widgets = { 'name': Input(attrs={ 'class': 'sections', 'id': 'name', 'spellcheck': 'false' }), 'rubric': Select(attrs={ 'class': 'sections', 'id': 'rubrics' }), 'photo': FileInput( attrs={ 'class': 'sections', 'id': 'photo', 'type': 'file', 'name': 'photo' }), 'user_score': NumberInput( attrs={ 'class': 'sections', 'id': 'din', 'type': 'number', 'name': 'assesiment', 'min': '1', 'max': '10', 'step': '0.1' }), 'info': Textarea(attrs={ 'name': 'link', 'id': 'info', 'class': 'sections' }), 'show_authorship': CheckboxInput() }
class Meta: model = Project exclude = ('recipient','location','status','album') labels = { 'name': _('ชื่อโครงการ'), 'desc': _('รายละเอียดโครงการ'), 'requiretype': _('การบริจาคที่รองรับ'), 'propose': _('จุดประสงค์โครงการ'), 'helping_people': _('จำนวนคนที่จะได้รับการช่วยเหลือ'), 'address': _('ที่อยู่ของผู้จะได้รับบริจาค'), } widgets = { 'name': TextInput(attrs={'class':'form-control'}), 'propose': TextInput(attrs={'class':'form-control'}), 'helping_people': NumberInput(attrs={'class':'form-control'}), 'address': Textarea(attrs={'cols': 40, 'rows': 5 , 'class':'form-control'}), 'desc': Textarea(attrs={'cols': 40, 'rows': 17 , 'class':'form-control'}), }
class BooleanResponseForm(forms.Form): confidence_percent = forms.DecimalField(widget=NumberInput(), label="Confidence assertion is true (percent)", required=False) def clean(self): cleaned_data = super().clean() conf = cleaned_data.get("confidence_percent") if conf < 0 or conf > 100: raise ValidationError(f"Confidence percentage ({conf}) out of bounds") if conf >= 50: cleaned_data["answer"] = True else: cleaned_data["answer"] = False cleaned_data["confidence_percent"] = 100 - conf return cleaned_data
class Meta: model = Donation fields = ['name', 'dtype', 'condition', 'desc', 'quantity'] labels = { 'name': _('ชื่อสิ่งของบริจาค'), 'dtype': _('ประเภท'), 'condition': _('สภาพ'), 'desc': _('คำอธิบายเกี่ยวกับสิ่งของบริจาค'), 'quantity': _('จำนวน'), } widgets = { 'name': TextInput(attrs={'class':'form-control'}), 'dtype': Select(attrs={'class':'form-control'}), 'condition': Select(attrs={'class':'form-control'}), 'quantity': NumberInput(attrs={'class':'form-control'}), 'desc': Textarea(attrs={'cols': 40, 'rows': 5 ,'class':'form-control'}), }
class FormItemPedido(forms.ModelForm): class Meta: model = PedidoItem fields = ['cantidad', 'precio'] cantidad = forms.IntegerField( initial=1, widget=NumberInput(attrs={ 'autofocus': 'autofocus', 'class': 'form-control' })) precio = forms.CharField( initial=0, required=False, widget=forms.NumberInput(attrs={ 'id': 'form_homework', 'step': '0.1', 'class': 'form-control' }))