class ClassRoomSelector(forms.Form): class_name = forms.ModelChoiceField(queryset=ClassRoom.objects.all(), help_text='Choose a class') attendance_date = forms.DateField(help_text="select the date to register")
def __init__(self, *args, **kwargs): fields = (forms.DateField(), forms.DateField()) super(DateRangeField, self).__init__(fields, *args, **kwargs)
class ArticleForm(forms.Form): campo1cf = forms.CharField() campo2df = forms.DateField()
class TrainingForm(forms.ModelForm): # DATE # 16 November, 2017 # %d %B, %y DATE_INPUT_FORMATS = ('%d %B, %Y',) # TIME # 03:00PM # TIME_INPUT_FORMATS = ('%I:%M%p',) name = forms.CharField(max_length=128) duration = forms.CharField(max_length=255) startD = forms.DateField( input_formats=DATE_INPUT_FORMATS, widget=forms.DateInput( attrs={'class': 'datepicker'} ) ) startT = forms.TimeField( input_formats=TIME_INPUT_FORMATS, widget=forms.TimeInput( attrs={'class': 'timepicker'} ) ) endD = forms.DateField( input_formats=DATE_INPUT_FORMATS, widget=forms.DateTimeInput( attrs={'class': 'datepicker'} ) ) endT = forms.TimeField( input_formats=TIME_INPUT_FORMATS, widget=forms.DateTimeInput( attrs={'class': 'timepicker'} ) ) type = forms.CharField(max_length=512) location = forms.CharField(max_length=255) lng = forms.DecimalField(max_digits=9, decimal_places=6) lat = forms.DecimalField(max_digits=9, decimal_places=6) training_image = forms.FileField(required=False) class Meta: model = Training fields = [ 'name', 'duration', 'startD', 'startT', 'endD', 'endT', 'type', 'location', 'lng', 'lat' ] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) print(self.user) super(TrainingForm, self).__init__(*args, **kwargs) # Super moze da se pise i bez argumenaTa!!!!!!! # pomocu __init sam odredio da ce ovo da mi bude prva metoda...Medjutim pomocu SUPER # sa sam pozvao *args i**kwargs iz trening forme tako da sad u ovoj funkciji imam to na raspolaganju def clean(self): data = self.cleaned_data if 'startD' not in data: raise ValidationError('Invalid fields detected') elif 'startT' not in data: raise ValidationError('Invalid fields detected') elif 'endD' not in data: raise ValidationError('Invalid fields detected') elif 'endT' not in data: raise ValidationError('Invalid fields detected') start = datetime( year = data['startD'].year, month = data['startD'].month, day = data['startD'].day, hour = data['startT'].hour, minute = data['startT'].minute, second = data['startT'].second, ) end = datetime( year = data['endD'].year, month = data['endD'].month, day = data['endD'].day, hour = data['endT'].hour, minute = data['endT'].minute, second = data['endT'].second, ) data['start'] = start data['end'] = end del data['startD'] del data['startT'] del data['endD'] del data['endT'] print(data) regUser = RegUser.objects.filter(user=self.user).first() overlapping_trainings = training_overlap_check(**data, trainer=regUser.trainer) if overlapping_trainings: raise ValidationError({ '__all__': 'Postoje treninzi koji se pokalapaju sa ovim vremenom', }) # dobijam reg usera preko__init__ # overlapping_trainings pozivam istoimenu funkciju i prosledjujem joj parametre return data
class SubscriptionForm(forms.Form): """ Use for existing subscriptions. Reason is to not validate credit card number but rather just check if it matches the one on record. """ first_name = forms.CharField(max_length=50, validators=[alphanumeric, required]) last_name = forms.CharField(max_length=50, validators=[alphanumeric, required]) cc_number = forms.CharField(max_length=255) date_cc_expiration = forms.DateField(widget=rpforms.MonthYearWidget()) address = forms.CharField(max_length=255, validators=[alphanumeric, required]) city = forms.CharField(max_length=255, validators=[alphanumeric, required]) state = forms.CharField(max_length=255, validators=[alphanumeric, required]) zip = forms.CharField(max_length=255, validators=[required, numeric]) country = forms.ChoiceField(choices=[('US', 'United States of America')]) cc_cvv = forms.CharField(validators=[required, numeric]) recurring = forms.NullBooleanField(widget=forms.CheckboxInput()) def clean_cc_number(self): """ do not validate_checksum """ data = str(self.cleaned_data['cc_number']) # completely new card number (no asterisks) if str(data).isdigit(): if rpccutils.validate_checksum(data) == False: raise forms.ValidationError(\ "Enter a valid credit card number.") if rpccutils.validate_cc_type(data) == False: raise forms.ValidationError(\ "Credit card type is not accepted.") else: # old card number data = data[-4:] if data != self.subscription.cc_number[-4:]: # also check if number changed raise forms.ValidationError(\ "Enter a valid credit card number.") return self.cleaned_data['cc_number'] def clean(self, *args, **kwargs): """ override the clean method. """ return self.cleaned_data def clean_recurring(self): data = self.cleaned_data['recurring'] if not data: raise forms.ValidationError("You must accept the Terms"+\ " & Conditions to continue.") return data def clean_date_cc_expiration(self): data = self.cleaned_data['date_cc_expiration'] now = datetime.datetime.now() if data.year == now.year: if data.month < now.month: raise forms.ValidationError("Your credit card has"+\ " expired!") return data
class BookingForm(forms.Form): doctorText = forms.CharField() date = forms.DateField(initial = datetime.date.today) date.widget.attrs = {'class': 'd'} time = forms.TimeField()
def addField(self, fieldtype, varname, label, options, **kwargs): field = None if fieldtype == 'FloatField': # float field = forms.FloatField(label=label, required=False) if fieldtype == 'AutoField': # int field = forms.IntegerField(label=label, required=False) if fieldtype == 'BooleanField': # boolean field = forms.NullBooleanField(label=label, required=False) if fieldtype == 'NullBooleanField': field = forms.NullBooleanField(label=label, required=False) if fieldtype == 'CharField' and not options: # str field = forms.CharField(label=label, required=False) if fieldtype == 'TextField': # str field = forms.TextField(label=label, required=False) if fieldtype == 'DateField': # date field = forms.DateField(widget=BootstrapDateInput(), label=label, required=False) if fieldtype == 'TimeField': # time field = forms.TimeField(widget=TimeWidget(), label=label, required=False) if fieldtype == 'DateTimeField': # datetime field = forms.DateTimeField(widget=DateTimeWidget(), label=label, required=False) if fieldtype == 8: # enum pass if fieldtype == 9: # hidden field = forms.CharField(widget=forms.HiddenInput(), label=label, required=False) if fieldtype == 'select': # select field = forms.ChoiceField(widget=forms.Select( attrs={ 'style': 'font-family: \'FontAwesome\', \'sans-serif\';' }), choices=options, label=label, required=False) self.select_vars.append(varname) if fieldtype == 11: # dateshort initial = self.getDefaultDate(initial) field = forms.DateField(label=label, required=False) if field: setattr(self, varname, field) self.fields[varname] = field else: raise Exception('missing field type %s' % fieldtype)
class SearchForm(forms.Form): min_sensing_date = forms.DateField(label='Od', required=False) max_sensing_date = forms.DateField(label='Do', required=False) min_ingestion_date = forms.DateField(label='Od', required=True, initial=datetime.datetime.now() - datetime.timedelta(days=7)) max_ingestion_date = forms.DateField(label='Do', required=True, initial=datetime.date.today) satellite = forms.ChoiceField(widget=forms.RadioSelect, choices=(('S1', 'S1'), ('S2', 'S2')), label='Satelita', required=True) orbit_direction = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label='Kierunek orbity', choices=(('ASCENDING', 'ASCENDING'), ('DESCENDING', 'DESCENDING')), required=False,) polarisation_mode = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label='Polaryzacja', choices=(('HH', 'HH'), ('HV', 'HV'), ('VH', 'VH'), ('VV', 'VV')), required=False) product_type = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label='Typ produktu', choices=(('GRD', 'GRD'), ('SLC', 'SLC'), ('RAW', 'RAW'), ('S2MSI2A', 'S2MSI2A'), ('S2MSI1C', 'S2MSI1C')), required=False) sensor_mode = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label='Tryb sensora', choices=(('IW', 'IW'), ('SM', 'SM'), ('EW', 'EW'), ('WV', 'WV')), required=False) cloud_cover = forms.DecimalField(label='Maksymalny % pokrywy chmur', required=False) relative_orbit_number = forms.IntegerField(label='Względny numer orbity', required=False) search_extent_min_x = forms.DecimalField(label='Minimalna długość geograficzna (λ)', required=False) search_extent_max_x = forms.DecimalField(label='Maksymalna długość geograficzna (λ)', required=False) search_extent_min_y = forms.DecimalField(label='Minimalna szerokość geograficzna (φ)', required=False) search_extent_max_y = forms.DecimalField(label='Maksymalna szerokość geograficzna (φ)', required=False) def clean(self): cleaned_data = super().clean() satellite = cleaned_data.get('satellite') product_type = set(cleaned_data.get('product_type')) cloud_cover = cleaned_data.get('cloud_cover') polarisation_mode = set(cleaned_data.get('polarisation_mode')) sensor_mode = set(cleaned_data.get('sensor_mode')) s1_product_type = {'GRD', 'SLC', 'RAW'} s2_product_type = {'S2MSI2A', 'S2MSI2A'} if satellite == 'S1' and (product_type.intersection(s2_product_type) or cloud_cover): raise forms.ValidationError("Wybrano satelitę S1 jednak otrzymano atrybuty S2") elif satellite == 'S2' and (product_type.intersection(s1_product_type) or polarisation_mode or sensor_mode): raise forms.ValidationError("Wybrano satelitę S2 jednak otrzymano atrybuty S1")
class createUserForm(forms.Form): username = forms.CharField(min_length=3, max_length=150) email = forms.EmailField(max_length=300) birthday = forms.DateField(input_formats=['%b-%d-%y']) phone_number = forms.CharField(min_length=12, max_length=12)
class TestForm(forms.Form): """ Form with a variety of widgets to test bootstrap3 rendering. """ date = forms.DateField(required=False) datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime(), required=False) subject = forms.CharField( max_length=100, help_text='my_help_text', required=True, widget=forms.TextInput(attrs={'placeholder': 'placeholdertest'}), ) password = forms.CharField(widget=forms.PasswordInput) message = forms.CharField(required=False, help_text='<i>my_help_text</i>') sender = forms.EmailField(label='Sender © unicode', help_text='E.g., "*****@*****.**"') secret = forms.CharField(initial=42, widget=forms.HiddenInput) weird = forms.CharField( help_text=u"strings are now utf-8 \u03BCnico\u0394é!") cc_myself = forms.BooleanField( required=False, help_text= 'cc stands for "carbon copy." You will get a copy in your mailbox.') select1 = forms.ChoiceField(choices=RADIO_CHOICES) select2 = forms.MultipleChoiceField( choices=RADIO_CHOICES, help_text='Check as many as you like.', ) select3 = forms.ChoiceField(choices=MEDIA_CHOICES) select4 = forms.MultipleChoiceField( choices=MEDIA_CHOICES, help_text='Check as many as you like.', ) category1 = forms.ChoiceField(choices=RADIO_CHOICES, widget=forms.RadioSelect) category2 = forms.MultipleChoiceField( choices=RADIO_CHOICES, widget=forms.CheckboxSelectMultiple, help_text='Check as many as you like.', ) category3 = forms.ChoiceField(widget=forms.RadioSelect, choices=MEDIA_CHOICES) category4 = forms.MultipleChoiceField( choices=MEDIA_CHOICES, widget=forms.CheckboxSelectMultiple, help_text='Check as many as you like.', ) number = forms.FloatField() url = forms.URLField() addon = forms.CharField(widget=forms.TextInput(attrs={ 'addon_before': 'before', 'addon_after': 'after' }), ) # TODO: Re-enable this after Django 1.11 #28105 is available # polygon = gisforms.PointField() required_css_class = 'bootstrap3-req' # Set this to allow tests to work properly in Django 1.10+ # More information, see issue #337 use_required_attribute = False def clean(self): cleaned_data = super(TestForm, self).clean() raise forms.ValidationError( "This error was added to show the non field errors styling.") return cleaned_data
class CalendarDaySearchForm(OwnedEntitiesForm): name__icontains = forms.CharField(label='Name', required=False) date__gte = forms.DateField(label='From date', required=False) date__lte = forms.DateField(label='To date', required=False)
def _process_date(field_json): field = forms.DateField() field.widget.input_type = "date" return field
class TestDateForm(forms.Form): testdatetime = forms.DateTimeField(required=True, label=u'datetime') testdate = forms.DateField(required=True, label=u'date') testtime = forms.TimeField(required=True, label=u'time')
def to_form_field(self, set_initial=True, enforce_required=True, for_csv_import=False): """ Return a form field suitable for setting a CustomField's value for an object. set_initial: Set initial date for the field. This should be False when generating a field for bulk editing. enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing. for_csv_import: Return a form field suitable for bulk import of objects in CSV format. """ initial = self.default if set_initial else None required = self.required if enforce_required else False # Integer if self.type == CustomFieldTypeChoices.TYPE_INTEGER: field = forms.IntegerField( required=required, initial=initial, min_value=self.validation_minimum, max_value=self.validation_maximum, ) # Boolean elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN: choices = ( (None, "---------"), (True, "True"), (False, "False"), ) field = forms.NullBooleanField( required=required, initial=initial, widget=StaticSelect2(choices=choices), ) # Date elif self.type == CustomFieldTypeChoices.TYPE_DATE: field = forms.DateField(required=required, initial=initial, widget=DatePicker()) # URL elif self.type == CustomFieldTypeChoices.TYPE_URL: field = LaxURLField(required=required, initial=initial) # Text elif self.type == CustomFieldTypeChoices.TYPE_TEXT: field = forms.CharField(max_length=255, required=required, initial=initial) if self.validation_regex: field.validators = [ RegexValidator( regex=self.validation_regex, message=mark_safe(f"Values must match this regex: <code>{self.validation_regex}</code>"), ) ] # Select or Multi-select else: choices = [(cfc.value, cfc.value) for cfc in self.choices.all()] default_choice = self.choices.filter(value=self.default).first() if not required or default_choice is None: choices = add_blank_choice(choices) # Set the initial value to the first available choice (if any) if set_initial and default_choice: initial = default_choice.value if self.type == CustomFieldTypeChoices.TYPE_SELECT: field_class = CSVChoiceField if for_csv_import else forms.ChoiceField field = field_class( choices=choices, required=required, initial=initial, widget=StaticSelect2(), ) else: field_class = CSVMultipleChoiceField if for_csv_import else forms.MultipleChoiceField field = field_class(choices=choices, required=required, initial=initial, widget=StaticSelect2Multiple()) field.model = self field.label = str(self) if self.description: field.help_text = self.description return field
class ActForm(forms.ModelForm): class Meta: model = Act exclude = ('cooperative_center_code', ) fields = '__all__' issue_date = forms.DateField(widget=forms.DateInput(format='%d/%m/%Y'), required=False, input_formats=('%d/%m/%Y', ), help_text='DD/MM/YYYY', label=_("Issue date")) publication_date = forms.DateField( widget=forms.DateInput(format='%d/%m/%Y'), required=False, input_formats=('%d/%m/%Y', ), help_text='DD/MM/YYYY', label=_("Publication date")) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) self.user_data = kwargs.pop('user_data', None) super(ActForm, self).__init__(*args, **kwargs) # context options lists based on act scope region if self.instance.id and self.instance.scope_region: region_id = self.instance.scope_region first_option = [('', '----------')] # create context lists and sort by name type_choices = [(s.id, unicode(s)) for s in ActType.objects.filter( Q(scope_region=None) | Q(scope_region=region_id))] type_choices.sort(key=lambda tup: tup[1]) scope_choices = [ (s.id, unicode(s)) for s in ActScope.objects.filter( Q(scope_region=None) | Q(scope_region=region_id)) ] scope_choices.sort(key=lambda tup: tup[1]) source_choices = [ (s.id, unicode(s)) for s in ActSource.objects.filter( Q(scope_region=None) | Q(scope_region=region_id)) ] source_choices.sort(key=lambda tup: tup[1]) organ_choices = [ (s.id, unicode(s)) for s in ActOrganIssuer.objects.filter( Q(scope_region=None) | Q(scope_region=region_id)) ] organ_choices.sort(key=lambda tup: tup[1]) state_choices = [ (s.id, unicode(s)) for s in ActState.objects.filter(scope_region=region_id) ] state_choices.sort(key=lambda tup: tup[1]) city_choices = [ (s.id, unicode(s)) for s in ActCity.objects.filter(scope_region=region_id) ] city_choices.sort(key=lambda tup: tup[1]) collection_choices = [(s.id, unicode(s)) for s in ActCollection.objects.all()] collection_choices.sort(key=lambda tup: tup[1]) self.fields['act_type'].choices = first_option + type_choices self.fields['scope'].choices = first_option + scope_choices self.fields['source_name'].choices = first_option + source_choices self.fields['organ_issuer'].choices = first_option + organ_choices self.fields['scope_state'].choices = first_option + state_choices self.fields['scope_city'].choices = first_option + city_choices self.fields[ 'act_collection'].choices = first_option + collection_choices else: empty_list = [('', '')] self.fields['act_type'].choices = empty_list self.fields['scope'].choices = empty_list self.fields['source_name'].choices = empty_list self.fields['organ_issuer'].choices = empty_list self.fields['scope_state'].choices = empty_list self.fields['scope_city'].choices = empty_list self.fields['act_collection'].choices = empty_list self.fields['issue_date'].widget.attrs['class'] = 'datepicker' self.fields['publication_date'].widget.attrs['class'] = 'datepicker' if self.user_data['service_role'].get('LeisRef') == 'doc': self.fields['status'].widget = widgets.HiddenInput() def save(self, *args, **kwargs): obj = super(ActForm, self).save(commit=False) # for fields with readonly attribute restore the original value for POST data insertions hack for name, field in self.fields.items(): if hasattr(field.widget.attrs, 'readonly'): setattr(obj, name, field.widget.original_value) # save modifications obj.save() return obj
class XlsxUpload(forms.Form): date = forms.DateField(label=u'日期', widget=forms.DateInput()) filename = forms.FileField(label=u'文件上传')
class ProfileForm(forms.Form): course = forms.CharField() col_name = forms.ChoiceField(choices=COLLEGES) birth_date = forms.DateField(widget=DatePicker)
class EditForm(forms.Form): """ This is the edit form, for editing an excisting online experiment """ title = forms.CharField(label='Choose a title') start_date = forms.DateField(required=False) end_date = forms.DateField(required=False)
class EditDateForm(forms.Form): edit_date_of_birth = forms.DateField(widget=DateInput)
class ScheduleBlockForm(forms.Form): start_time = forms.DateTimeField( widget=forms.DateTimeInput(attrs={'style': 'width: 200px;'}), input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S']) end_time = forms.DateTimeField( widget=forms.DateTimeInput(attrs={'style': 'width: 200px;'}), input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S']) exp_count = forms.IntegerField(widget=forms.HiddenInput(), required=False) exp_length = forms.FloatField(widget=forms.NumberInput( attrs={'size': '5'})) slot_length = forms.FloatField( widget=forms.NumberInput(attrs={'size': '5'}), required=False) filter_pattern = forms.CharField(widget=forms.TextInput( attrs={'size': '20'})) pattern_iterations = forms.FloatField(widget=forms.HiddenInput(), required=False) proposal_code = forms.CharField(max_length=20, widget=forms.HiddenInput()) site_code = forms.CharField(max_length=5, widget=forms.HiddenInput()) group_name = forms.CharField( max_length=50, widget=forms.TextInput( attrs={ 'style': 'text-align: right; width: -webkit-fill-available; width: -moz-available;' })) utc_date = forms.DateField(input_formats=[ '%Y-%m-%d', ], widget=forms.HiddenInput(), required=False) jitter = forms.FloatField(widget=forms.NumberInput(attrs={'size': '5'}), required=False) period = forms.FloatField(widget=forms.NumberInput(attrs={'size': '5'}), required=False) bin_mode = forms.ChoiceField(required=False, choices=BIN_MODES) spectroscopy = forms.BooleanField(required=False, widget=forms.HiddenInput()) too_mode = forms.BooleanField(required=False, widget=forms.HiddenInput()) calibs = forms.ChoiceField(required=False, widget=forms.HiddenInput(), choices=CALIBS) instrument_code = forms.CharField(max_length=10, widget=forms.HiddenInput(), required=False) solar_analog = forms.BooleanField(initial=True, widget=forms.HiddenInput(), required=False) calibsource_id = forms.IntegerField(widget=forms.HiddenInput(), required=False) calibsource_exptime = forms.IntegerField( widget=forms.NumberInput(attrs={'size': '5'}), required=False) calibsource_list = forms.ChoiceField(required=False) max_airmass = forms.FloatField( widget=forms.NumberInput(attrs={'style': 'width: 75px;'}), required=False) ipp_value = forms.FloatField( widget=forms.NumberInput(attrs={'style': 'width: 75px;'}), required=False) para_angle = forms.BooleanField(initial=False, required=False) min_lunar_dist = forms.FloatField( widget=forms.NumberInput(attrs={'style': 'width: 75px;'}), required=False) acceptability_threshold = forms.FloatField( widget=forms.NumberInput(attrs={'style': 'width: 75px;'}), required=False) ag_exp_time = forms.FloatField( widget=forms.NumberInput(attrs={'style': 'width: 75px;'}), required=False) edit_window = forms.BooleanField( initial=False, required=False, widget=forms.CheckboxInput(attrs={'class': 'window-switch'})) add_dither = forms.BooleanField( initial=False, required=False, widget=forms.CheckboxInput(attrs={'class': 'dither-switch'})) dither_distance = forms.FloatField( widget=forms.NumberInput(attrs={'style': 'width: 75px;'}), required=False) fractional_rate = forms.ChoiceField(required=False, choices=RATE_OPTIONS) speed = forms.FloatField(widget=forms.HiddenInput(), required=False) gp_explength = forms.FloatField( required=False, widget=forms.NumberInput(attrs={'size': '5'})) rp_explength = forms.FloatField( required=False, widget=forms.NumberInput(attrs={'size': '5'})) ip_explength = forms.FloatField( required=False, widget=forms.NumberInput(attrs={'size': '5'})) zp_explength = forms.FloatField( required=False, widget=forms.NumberInput(attrs={'size': '5'})) muscat_sync = forms.BooleanField(initial=False, required=False) def clean_fractional_rate(self): """Ensure Float""" try: return float(self.cleaned_data['fractional_rate']) except ValueError: return 0.5 def clean_dither_distance(self): """Limit dither distance to values between 0 and 60 arcsec.""" if not self.cleaned_data[ 'dither_distance'] or self.cleaned_data['dither_distance'] < 0: return 10 if self.cleaned_data['dither_distance'] > 60: return 60 return self.cleaned_data['dither_distance'] def clean_exp_length(self): if not self.cleaned_data[ 'exp_length'] or self.cleaned_data['exp_length'] < 0.1: return 0.1 else: return self.cleaned_data['exp_length'] def clean_min_lunar_dist(self): if self.cleaned_data['min_lunar_dist'] > 180: return 180 elif self.cleaned_data['min_lunar_dist'] < 0: return 0 else: return self.cleaned_data['min_lunar_dist'] def clean_acceptability_threshold(self): if self.cleaned_data['acceptability_threshold'] > 100: return 100 elif self.cleaned_data['acceptability_threshold'] < 0: return 0 else: return self.cleaned_data['acceptability_threshold'] def clean_ag_exp_time(self): if self.cleaned_data['ag_exp_time'] is not None and self.cleaned_data[ 'ag_exp_time'] < 0.1: return 0.1 elif self.cleaned_data['ag_exp_time'] is None: return None else: return self.cleaned_data['ag_exp_time'] def clean_ipp_value(self): if self.cleaned_data['ipp_value'] < 0.5: return 0.5 elif self.cleaned_data['ipp_value'] > 2: return 2.0 else: return self.cleaned_data['ipp_value'] def clean_max_airmass(self): if self.cleaned_data['max_airmass'] < 1: return 1.0 else: return self.cleaned_data['max_airmass'] def clean_start_time(self): start = self.cleaned_data['start_time'] window_cutoff = datetime.utcnow() - timedelta(days=1) if start <= window_cutoff: return datetime.utcnow().replace(microsecond=0) else: return self.cleaned_data['start_time'] def clean_end_time(self): end = self.cleaned_data['end_time'] if end <= datetime.utcnow(): raise forms.ValidationError("Window cannot end in the past") else: return self.cleaned_data['end_time'] def clean_filter_pattern(self): try: pattern = self.cleaned_data['filter_pattern'] stripped_pattern = pattern.replace(" ", ",").replace(";", ",").replace( "/", ",") chunks = stripped_pattern.split(',') chunks = list(filter(None, chunks)) if chunks.count(chunks[0]) == len(chunks): chunks = [chunks[0]] cleaned_filter_pattern = ",".join(chunks) except KeyError: cleaned_filter_pattern = '' except IndexError: cleaned_filter_pattern = '' return cleaned_filter_pattern def clean_period(self): if self.cleaned_data[ 'period'] is not None and self.cleaned_data['period'] < 0.02: return 0.02 else: return self.cleaned_data['period'] def clean_slot_length(self): if self.cleaned_data['slot_length'] is None: return 0 else: return self.cleaned_data['slot_length'] def clean(self): cleaned_data = super(ScheduleBlockForm, self).clean() site = self.cleaned_data['site_code'] spectra = self.cleaned_data['spectroscopy'] filter_list, fetch_error = fetch_filter_list(site, spectra) if fetch_error: raise forms.ValidationError(fetch_error) try: if not self.cleaned_data['filter_pattern']: raise forms.ValidationError("You must select a filter.") except KeyError: raise forms.ValidationError( 'Dude, you had to actively input a bunch of spaces and nothing else to see this error. ' 'Why?? Just pick a filter from the list! %(filters)s', params={'filters': ",".join(filter_list)}) pattern = self.cleaned_data['filter_pattern'] chunks = pattern.split(',') bad_filters = [x for x in chunks if x not in filter_list] if len(bad_filters) > 0: if len(bad_filters) == 1: raise forms.ValidationError( '%(bad)s is not an acceptable filter at this site.', params={'bad': ",".join(bad_filters)}) else: raise forms.ValidationError( '%(bad)s are not acceptable filters at this site.', params={'bad': ",".join(bad_filters)}) elif self.cleaned_data['exp_count'] == 0: raise forms.ValidationError("There must be more than 1 exposure") if self.cleaned_data.get('end_time') and self.cleaned_data.get( 'start_time'): window_width = self.cleaned_data['end_time'] - self.cleaned_data[ 'start_time'] window_width = window_width.total_seconds() / 60 if window_width < self.cleaned_data['slot_length']: raise forms.ValidationError( "Requested Observations will not fit within Scheduling Window." ) if self.cleaned_data.get('end_time') < self.cleaned_data.get( 'start_time'): raise forms.ValidationError( "Scheduling Window cannot end before it begins without breaking causality. Please Fix." ) return cleaned_data def __init__(self, *args, **kwargs): self.calibsource_list = kwargs.pop('calibsource_list', None) super(ScheduleBlockForm, self).__init__(*args, **kwargs) self.fields['calibsource_list'].choices = ANALOG_OPTIONS
class Meta: model = Documento exclude = ('slug', ) f_actualizacion = forms.DateField(widget=BootstrapDateInput( attrs={}, ), )
class UpdateTerminationDate(forms.Form): Employee_ID = forms.CharField(max_length=12, required=True) Termination_Date = forms.DateField(required=True)
class DataSelectionForm(forms.Form): two_column_format = True title = forms.CharField( required=False, widget=forms.HiddenInput(attrs={'class': 'hidden_form_title'})) description = forms.CharField( required=False, widget=forms.HiddenInput(attrs={'class': 'hidden_form_description'})) satellite = forms.ModelChoiceField( queryset=Satellite.objects.all(), widget=forms.HiddenInput(attrs={'class': 'hidden_form_satellite'})) area_id = forms.CharField(widget=forms.HiddenInput( attrs={'class': 'hidden_form_id'})) latitude_min = forms.FloatField( label='Min Latitude', widget=forms.NumberInput(attrs={ 'class': 'field-divided', 'step': "any", 'required': 'required' })) latitude_max = forms.FloatField( label='Max Latitude', widget=forms.NumberInput(attrs={ 'class': 'field-divided', 'step': "any", 'required': 'required' })) longitude_min = forms.FloatField( label='Min Longitude', widget=forms.NumberInput(attrs={ 'class': 'field-divided', 'step': "any", 'required': 'required' })) longitude_max = forms.FloatField( label='Max Longitude', widget=forms.NumberInput(attrs={ 'class': 'field-divided', 'step': "any", 'required': 'required' })) time_start = forms.DateField(label='Start Date', widget=forms.DateInput( attrs={ 'class': 'datepicker field-divided', 'placeholder': '01/01/2010', 'required': 'required' })) time_end = forms.DateField(label='End Date', widget=forms.DateInput( attrs={ 'class': 'datepicker field-divided', 'placeholder': '01/02/2010', 'required': 'required' })) def __init__(self, *args, **kwargs): time_start = kwargs.pop('time_start', None) time_end = kwargs.pop('time_end', None) area = kwargs.pop('area', None) self.user_id = kwargs.pop('user_id', None) self.user_history = kwargs.pop('user_history', None) self.task_model_class = kwargs.pop('task_model_class', None) super(DataSelectionForm, self).__init__(*args, **kwargs) #meant to prevent this routine from running if trying to init from querydict. if time_start and time_end: self.fields['time_start'] = forms.DateField( initial=time_start.strftime("%m/%d/%Y"), label='Start Date', widget=forms.DateInput(attrs={ 'class': 'datepicker field-divided', 'required': 'required' })) self.fields['time_end'] = forms.DateField( initial=time_end.strftime("%m/%d/%Y"), label='End Date', widget=forms.DateInput(attrs={ 'class': 'datepicker field-divided', 'required': 'required' })) if area: self.fields['latitude_min'].widget.attrs.update({ 'min': area.latitude_min, 'max': area.latitude_max }) self.fields['latitude_max'].widget.attrs.update({ 'min': area.latitude_min, 'max': area.latitude_max }) self.fields['longitude_min'].widget.attrs.update({ 'min': area.longitude_min, 'max': area.longitude_max }) self.fields['longitude_max'].widget.attrs.update({ 'min': area.longitude_min, 'max': area.longitude_max }) def clean(self): cleaned_data = super(DataSelectionForm, self).clean() if cleaned_data.get('latitude_min') >= cleaned_data.get( 'latitude_max'): self.add_error( 'latitude_min', "Please enter a valid pair of latitude values where the lower bound is less than the upper bound." ) if cleaned_data.get('longitude_min') >= cleaned_data.get( 'longitude_max'): self.add_error( 'longitude_min', "Please enter a valid pair of longitude values where the lower bound is less than the upper bound." ) # The start and end time fields are removed in some apps (e.g. spectral_anomaly), # so we may not perform checks on these fields. time_start, time_end = cleaned_data.get( 'time_start'), cleaned_data.get('time_end') if time_start is not None and time_end is not None and (time_start >= time_end): self.add_error( 'time_start', "Please enter a valid start and end time range where the start is before the end." ) area = (cleaned_data.get('latitude_max') - cleaned_data.get('latitude_min')) * ( cleaned_data.get('longitude_max') - cleaned_data.get('longitude_min')) # Limit the area allowed. max_area = 1 if area > max_area: self.add_error( 'latitude_min', 'Tasks over an area greater than {} ' 'square degree(s) are not permitted.'.format(max_area)) # Limit the time range allowed. if time_start is not None and time_end is not None: # For some apps, the time extent is not relevant to resource consumption # (e.g. if data is only loaded for the first and last years). from apps.coastal_change.models import CoastalChangeTask if self.task_model_class not in [CoastalChangeTask]: if self.check_time_range(time_start, time_end, MAX_NUM_YEARS): self.add_error( 'time_start', 'Tasks over a time range greater than {} ' 'year(s) are not permitted.'.format(MAX_NUM_YEARS)) # Limit each user to some number of queued tasks across all apps. if MAX_NUM_TASKS_PER_USER is not None: num_running_tasks = self.task_model_class.get_queryset_from_history( self.user_history, complete=False).count() if num_running_tasks >= MAX_NUM_TASKS_PER_USER: self.add_error( None, 'You may only run {} task(s) at a time.'.format( MAX_NUM_TASKS_PER_USER)) return cleaned_data def check_time_range(self, time_start, time_end, max_num_years=5): """ Determines if the time range [time_start, time_end] exceeds an upper bound. If so, returns `True`. Parameters ---------- time_start, time_end: datetime.date max_num_years: float (default 5) The maximum number of years the time range can have. """ year_diff = time_end.year - time_start.year month_diff = time_end.month - time_start.month day_diff = time_end.day - time_start.day return (year_diff > max_num_years) or \ (year_diff == max_num_years and month_diff > 0) or \ (year_diff == max_num_years and month_diff == 0 and day_diff > 0)
class SignUpForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Username' })) dob = forms.DateField(widget=forms.DateInput(attrs={ 'class': 'form-control', 'type': 'date' })) email = forms.EmailField(widget=forms.EmailInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Email' })) password1 = forms.CharField( label='Password', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password' })) password2 = forms.CharField( label='Confirm Password', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Confirm Password' })) def clean_username(self, *args, **kwargs): username = self.cleaned_data.get('username') qs = get_user_model().objects.filter(username=username) if qs.exists(): raise forms.ValidationError('Username has already been taken!') else: return username def clean_dob(self, *args, **kwargs): dob = self.cleaned_data['dob'] today = date.today() if (dob.year + 13, dob.month, dob.day) > (today.year, today.month, today.day): raise forms.ValidationError( 'Must be at least 13 or older to register') else: return dob def clean_email(self, *args, **kwargs): email = self.cleaned_data.get('email') qs = get_user_model().objects.filter(email=email) if qs.exists(): raise forms.ValidationError('Email has already been registered!') else: return email def clean_password2(self, *args, **kwargs): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('Passwords did not match!') else: return password2 def save(self, commit=True): user = super(SignUpForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() group = Group.objects.get_or_create(name='LoopUser') user.groups.add(Group.objects.get(name='LoopUser')) user.save() return user class Meta: model = CustomUser fields = ( 'username', 'dob', 'email', 'password1', 'password2', )
class ArticleForm(forms.Form): title = forms.CharField() pub_date = forms.DateField()
class SearchPeriodo(forms.Form): dt_inicio = forms.DateField() dt_fim = forms.DateField()
class AlbumForm(forms.ModelForm): relase_date = forms.DateField(widget=forms.TextInput(attrs={'type':'date'})) class Meta: model = models.Album fields = "__all__"
class UserStatusForm(happyforms.ModelForm): """Form for displaying info regarding the availability status of a user.""" start_date = forms.DateField(input_formats=['%d %B %Y']) expected_date = forms.DateField(input_formats=['%d %B %Y']) is_replaced = forms.BooleanField(widget=forms.RadioSelect( choices=BOOLEAN_CHOICES, attrs={'id': 'id_is_replaced'}), required=False) def __init__(self, *args, **kwargs): super(UserStatusForm, self).__init__(*args, **kwargs) query = (User.objects.filter( groups__name='Rep', userprofile__registration_complete=True) .exclude(id=self.instance.user.id).order_by('first_name')) self.fields['replacement_rep'].queryset = query if self.instance.id: self.fields['expected_date'].widget = forms.HiddenInput() self.fields['start_date'].widget = forms.HiddenInput() self.fields['start_date'].required = False def clean(self): """Clean Form.""" cdata = super(UserStatusForm, self).clean() if self.instance.id: cdata['start_date'] = self.instance.start_date return cdata tomorrow = get_date(days=1) today = get_date() max_period = get_date(weeks=MAX_UNAVAILABILITY_PERIOD) if 'start_date' in cdata: if cdata['start_date'] < today: msg = u'Start date cannot be in the past.' self._errors['start_date'] = self.error_class([msg]) if 'expected_date' in cdata: if cdata['expected_date'] < tomorrow: msg = (u'Return day cannot be earlier than {0}' .format(tomorrow.strftime('%d %B %Y'))) self._errors['expected_date'] = self.error_class([msg]) if cdata['expected_date'] < cdata['start_date']: msg = u'Return date cannot be before start date.' self._errors['expected_date'] = self.error_class([msg]) if cdata['expected_date'] > max_period: msg = (u'The maximum period for unavailability is until {0}.' .format(max_period.strftime('%d %B %Y'))) sop = mark_safe(msg + (' For more information please check ' 'the %s Leaving SOP') % LEAVING_SOP_URL) self._errors['expected_date'] = self.error_class([sop]) if ('is_replaced' in cdata and cdata['is_replaced'] and not cdata['replacement_rep']): msg = 'Please select a replacement Rep during your absence.' self._errors['replacement_rep'] = self.error_class([msg]) return cdata class Meta: model = UserStatus fields = ['start_date', 'expected_date', 'replacement_rep']
class BankForm(forms.Form): branch_name = forms.CharField() """ Personal Details """ person_title = forms.ChoiceField(choices=(('Mr', 'Mr.'), ('Mrs.', 'Mrs.'), ('Ms.', 'Ms.')), label='Title') full_name = forms.CharField() date_of_birth = forms.DateField() email = forms.EmailField() parent_name = forms.CharField(label='Nel caso di iscrizione ad un albo indicare quale') nationality = forms.ChoiceField(choices=()) mobile_no = forms.CharField() existing_bank_account = forms.CharField() partner_name = forms.CharField(label='Descrizione dell Ordine') """ Residential address """ flat_bulding = forms.CharField(label='Numero di iscrizione e tipo di sezione') road_no = forms.CharField(label='Numero di ...') area_and_landmark = forms.CharField(label='Luogo di esercizio') telephone_residence = forms.CharField() city = forms.CharField() office = forms.CharField() fax = forms.CharField() pin_code = forms.CharField() """ Mailing Address """ mailing_company_details = forms.CharField(label="Denominazione dello studio") mailing_road_no = forms.CharField(label='Road no./name') mailing_area_and_landmark = forms.CharField(label='Area and landmark') mailing_city = forms.CharField(label='City') mailing_mobile = forms.CharField(label='Mobile No.') mailing_telephone_residence = forms.CharField(label='Telephone Residence') mailing_office = forms.CharField(label='Office') mailing_fax = forms.CharField(label='Fax') mailing_pin_code = forms.CharField(label='Pin Code') mailing_email = forms.EmailField(label='E-mail') """ Details of Introduction by Existing Customer """ introducer_name = forms.CharField(label='Customer Name') introducer_account_no = forms.CharField(label='Account No.') introducer_signature = forms.CharField(label="Introducer's signature") """ Account Details """ account_type = forms.ChoiceField( choices=(('S', 'Savings'), ('C', 'Current'), ('F', 'Fixed deposits')), label='Choice of account', widget=forms.RadioSelect) account_mode = forms.ChoiceField( choices=(('CS', 'Cash'), ('CQ', 'Cheque'), ('NF', 'NEFT')), label='Mode of funding', widget=forms.RadioSelect) account_amount = forms.FloatField(label='Amount') """ Details of Fixed Deposit """ deposit_type = forms.ChoiceField( choices=(('O', 'Ordinary'), ('C', 'Cumulative')), label='Types of deposit', widget=forms.RadioSelect) deposit_mode = forms.ChoiceField( choices=(('CS', 'Cash'), ('CQ', 'Cheque'), ('NF', 'NEFT')), label='Mode of funding', widget=forms.RadioSelect) deposit_amount = forms.FloatField(label='Amount') deposit_no = forms.CharField(label='No. of deposits') deposit_individual_amount = forms.FloatField(label='Individual Deposit Amount') """ Personal Details """ occupation = forms.ChoiceField( choices=(('NE', 'Non-executive'), ('HW', 'Housewife'), ('RT', 'Retired'), ('ST', 'Student'), ('OT', 'Other'), ('UN', 'Unemployed')), widget=forms.RadioSelect) job_title = forms.CharField() department = forms.CharField() nature_of_business = forms.CharField() education = forms.ChoiceField( choices=(('UG', 'Under graduate'), ('GR', 'Graduate'), ('OT', 'Others')), widget=forms.RadioSelect) montly_income = forms.ChoiceField( choices=(('000', 'Zero Income'), ('L10', 'Less than $10,000'), ('G10', '$10,000+')), widget=forms.RadioSelect) martial_status = forms.ChoiceField( choices=(('M', 'Married'), ('S', 'Single')), widget=forms.RadioSelect) spouse_name = forms.CharField() """ Other existing bank accounts, if any """ other_account1 = forms.CharField(label='Name of the Bank / branch') other_account2 = forms.CharField(label='Name of the Bank / branch') """ Reason for Account opening """ reason = forms.CharField(label="Please specify", widget=forms.Textarea) """ Terms And Conditions """ terms_accepted = forms.BooleanField( label="I/We confirm having read and understood the account rules of The Banking Corporation Limited" " ('the Bank'), and hereby agree to be bound by the terms and conditions and amendments governing the" " account(s) issued by the Bank from time-to-time.") layout = Layout( Fieldset("Please open an account at", 'branch_name'), Fieldset("Personal Details (Sole/First Accountholder/Minor)", Row(Span2('person_title'), Span10('full_name')), Row(Column('date_of_birth', 'email', 'parent_name'), Column('nationality', Row('mobile_no', 'existing_bank_account'), 'partner_name'))), Fieldset('Residential address', Row('flat_bulding', 'road_no'), Row(Span10('area_and_landmark'), Span2('city')), Row('telephone_residence', 'office', 'fax', 'pin_code')), Fieldset("Mailing Address (If different from the First Accountholder's address)", 'mailing_company_details', Row('mailing_road_no', 'mailing_area_and_landmark', 'mailing_city', 'mailing_mobile'), Row('mailing_telephone_residence', 'mailing_office', 'mailing_fax', 'mailing_pin_code'), 'mailing_email'), Fieldset("Details of Introduction by Existing Customer (If applicable)", Row('introducer_name', 'introducer_account_no'), 'introducer_signature'), Fieldset("Account Details", Row('account_type', 'account_mode'), 'account_amount'), Fieldset("Details of Fixed Deposit", Row('deposit_type', 'deposit_mode'), Row(Span6('deposit_amount'), Span3('deposit_no'), Span3('deposit_individual_amount'))), Fieldset("Personal Details", Row('occupation', 'education', 'montly_income'), 'job_title', Row('department', 'nature_of_business'), Row('martial_status', 'spouse_name')), Fieldset("Other existing bank accounts, if any", Row('other_account1', 'other_account2')), Fieldset("Reason for Account opening", 'reason'), Fieldset("Terms And Conditions", 'terms_accepted') )
class OrderSearchForm(forms.Form): date_from = forms.DateField(required=False, label=pgettext_lazy("start date", "From"), widget=widgets.DatePickerInput()) date_to = forms.DateField(required=False, label=pgettext_lazy("end date", "To"), widget=widgets.DatePickerInput()) order_number = forms.CharField(required=False, label=_("Order number")) def clean(self): if self.is_valid() and not any([ self.cleaned_data['date_from'], self.cleaned_data['date_to'], self.cleaned_data['order_number'] ]): raise forms.ValidationError(_("At least one field is required.")) return super(OrderSearchForm, self).clean() def description(self): """ Uses the form's data to build a useful description of what orders are listed. """ if not self.is_bound or not self.is_valid(): return _('All orders') else: date_from = self.cleaned_data['date_from'] date_to = self.cleaned_data['date_to'] order_number = self.cleaned_data['order_number'] return self._orders_description(date_from, date_to, order_number) def _orders_description(self, date_from, date_to, order_number): if date_from and date_to: if order_number: desc = _('Orders placed between %(date_from)s and ' '%(date_to)s and order number containing ' '%(order_number)s') else: desc = _('Orders placed between %(date_from)s and ' '%(date_to)s') elif date_from: if order_number: desc = _('Orders placed since %(date_from)s and ' 'order number containing %(order_number)s') else: desc = _('Orders placed since %(date_from)s') elif date_to: if order_number: desc = _('Orders placed until %(date_to)s and ' 'order number containing %(order_number)s') else: desc = _('Orders placed until %(date_to)s') elif order_number: desc = _('Orders with order number containing %(order_number)s') else: return None params = { 'date_from': date_from, 'date_to': date_to, 'order_number': order_number, } return desc % params def get_filters(self): date_from = self.cleaned_data['date_from'] date_to = self.cleaned_data['date_to'] order_number = self.cleaned_data['order_number'] kwargs = {} if date_from and date_to: kwargs['date_placed__range'] = [date_from, date_to] elif date_from and not date_to: kwargs['date_placed__gt'] = date_from elif not date_from and date_to: kwargs['date_placed__lt'] = date_to if order_number: kwargs['number__contains'] = order_number return kwargs