class ProductForm(forms.Form): producut_type_choices = [('stockable', 'Stockable'), ('consumable', 'Consumable'), ('service', 'Service')] status = [('development', 'In developemt'), ('normal', 'Normal'), ('end', 'End of Life Cycle'), ('obsolete', 'Obsolote')] image = forms.ImageField() name = forms.CharField(label='Product Name', max_length=300, required=True) sell_ok = forms.BooleanField(label='Can be sold') purchase_ok = forms.BooleanField(label='Can be purchased') product_type = forms.ChoiceField(label='Product Type', choices=producut_type_choices) sale_price = forms.FloatField(label='Sale Price') cost_price = forms.FloatField(label='Cost Price') product_status = forms.ChoiceField(label='Status', choices=status) description = forms.CharField(label='Product Description', widget=forms.Textarea) quantity_on_hand = forms.IntegerField(label='Quantity On Hand') product_manager = forms.ModelChoiceField( queryset=User.objects.all(), empty_label='Select product manager', label='Product Manager') rack = forms.CharField(label='Rack') row = forms.CharField(label='Row') case = forms.CharField(label='Case') warranty = forms.DurationField(label='Warranty') lead_time = forms.DurationField(label='Customer Lead TIme') description_purchase = forms.CharField(label='Purchase Description', widget=forms.Textarea) description_sale = forms.CharField(label='Sales Description', widget=forms.Textarea)
class FilterForm(forms.Form): min_length = forms.DurationField(widget=forms.TimeInput) max_length = forms.DurationField() min_date = forms.DateField(widget=forms.DateInput) max_date = forms.DateField(widget=forms.SelectDateWidget) order_by = forms.ChoiceField(choices=[('test', 'date')]) ascending = forms.BooleanField()
class TestCaseForm(forms.ModelForm): class Meta: model = TestCase exclude = [ # pylint: disable=modelform-uses-exclude "reviewer", "tag", "component", "plan", ] default_tester = UserField(required=False) priority = forms.ModelChoiceField( queryset=Priority.objects.filter(is_active=True), empty_label=None, ) product = forms.ModelChoiceField( queryset=Product.objects.all(), empty_label=None, ) setup_duration = forms.DurationField( widget=DurationWidget(), required=False, ) testing_duration = forms.DurationField( widget=DurationWidget(), required=False, ) text = forms.CharField( widget=SimpleMDE(), required=False, initial=_( """**Scenario**: ... what behavior will be tested ... **Given** ... conditions ... **When** ... actions ... **Then** ... expected results ... *Actions*: 1. item 2. item 3. item *Expected results*: 1. item 2. item 3. item""" ), ) def populate(self, product_id=None): if product_id: self.fields["category"].queryset = Category.objects.filter( product_id=product_id ) else: self.fields["category"].queryset = Category.objects.all()
class ScheduleForm(forms.Form): elephant = forms.ModelChoiceField(queryset=Elephant.objects.all()) start_time = forms.DateTimeField(initial=datetime.now()) end_time = forms.DateTimeField(initial=datetime.now() + timedelta(hours=8)) interval = forms.DurationField() max_feeds = forms.IntegerField() '''
class VideoForm(forms.ModelForm): sync_help_chat_timestamp = forms.IntegerField(required=False, localize=True, label='Chat timestamp') sync_help_video_timestamp = forms.DurationField(required=False, label='Video timestamp') def clean(self): cleaned_data = super().clean() # Set the chat start timestamp from sync helper values. if cleaned_data.get('chat_start', None) is None: sync_chat_timestamp = cleaned_data.get('sync_help_chat_timestamp') sync_video_timestamp = cleaned_data.get( 'sync_help_video_timestamp') if sync_chat_timestamp and sync_video_timestamp: chat_start_offset = int(sync_video_timestamp.total_seconds() * 1000) cleaned_data[ 'chat_start'] = sync_chat_timestamp - chat_start_offset return cleaned_data class Meta: model = models.Video exclude = ('duration', ) labels = { 'url': 'URL', }
class ShiftForm(forms.ModelForm): # shiftForm clock_in = forms.TimeField( label='Clock In ', widget=forms.TimeInput(attrs={ "class": "form-control", "placeholder": "hour:min:sec" })) clock_out = forms.TimeField( label='Clock Out', widget=forms.TimeInput(attrs={ "class": "form-control", "placeholder": "hour:min:sec" })) break_time = forms.DurationField( label='Break', widget=forms.TimeInput(attrs={ "class": "form-control", "placeholder": "hour:min:sec" })) date = forms.DateField(widget=forms.SelectDateWidget(attrs={"class": ""})) class Meta(): model = Shift fields = ['name', 'description']
class SubChapterForm(forms.ModelForm): duration = forms.DurationField( required=False, widget=forms.TextInput(attrs={"placeholder": "hh:mm:ss"})) initial_code_output = forms.CharField(required=False, widget=forms.Textarea) hint_code_output = forms.CharField(required=False, widget=forms.Textarea) solution_code_output = forms.CharField(required=False, widget=forms.Textarea) class Meta: model = SubChapter fields = ( "position", "title", "description", "instructions", "duration", "error_message", "initial_code", "initial_code_output", "hint_code", "hint_code_output", "check_by", "solution_code", "solution_code_output", )
class FilterObjectsForm(forms.Form): """Form for filtering a table of alerted objects Fields: time_range (``DurationField``) min_ra (``FloatField``) max_ra (``FloatField``) min_dec (``FloatField``) max_dec (``FloatField``) """ time_range = forms.DurationField(required=False, label='Publication time') min_ra = forms.FloatField(required=False, label='Min RA', widget=forms.TextInput()) max_ra = forms.FloatField(required=False, label='Max RA', widget=forms.TextInput()) min_dec = forms.FloatField(required=False, label='Min Dec', widget=forms.TextInput()) max_dec = forms.FloatField(required=False, label='Max Dec', widget=forms.TextInput())
class XMLRPCBaseCaseForm(BaseCaseForm): estimated_time = forms.DurationField(required=False) is_automated = forms.ChoiceField( choices=FULL_AUTOMATED_CHOICES, widget=forms.CheckboxSelectMultiple(), required=False, )
class ManyFieldsExampleForm(forms.Form): hiddeninput = forms.CharField(widget=forms.HiddenInput()) multiplehiddeninput = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput, choices=CONTINENTS) modelchoicefield = forms.ModelChoiceField(queryset=Friend.objects.all(), empty_label="Empty Space", to_field_name="first_name") modelchoicefield2 = forms.ModelChoiceField(queryset=Friend.objects.all(), to_field_name="first_name") modelmultiplechoicefield = forms.ModelMultipleChoiceField(queryset=Friend.objects.all()) booleanfield = forms.BooleanField(label="BooleanField") charfield = forms.CharField(label="CharField") choicefield = forms.ChoiceField(label="ChoiceField", choices=CONTINENTS) typedchoicefield = forms.TypedChoiceField(label="TypedChoiceField") datefield = forms.DateField(label="DateField") datetimefield = forms.DateTimeField(label="DateTimeField") decimalfield = forms.DecimalField(label="DecimalField") durationfield = forms.DurationField(label="DurationField") emailfield = forms.EmailField(label="EmailField") filefield = forms.FileField(label="FileField") filepathfield = forms.FilePathField(label="FilePathField", path="/") floatfield = forms.FloatField(label="FloatField") imagefield = forms.ImageField(label="ImageField") integerfield = forms.IntegerField(label="IntegerField") genericipaddressfield = forms.GenericIPAddressField(label="GenericIPAddressField") multiplechoicefield = forms.MultipleChoiceField(label="MultipleChoiceField", choices=CONTINENTS) typedmultiplechoicefield = forms.TypedMultipleChoiceField(label="TypedMultipleChoiceField", choices=CONTINENTS) nullbooleanfield = forms.NullBooleanField(label="NullBooleanField") slugfield = forms.SlugField(label="SlugField") timefield = forms.TimeField(label="TimeField") urlfield = forms.URLField(label="URLField") uuidfield = forms.UUIDField(label="UUIDField")
class NewLectureForm(forms.ModelForm): duration = forms.DurationField(initial=datetime.timedelta(days=0, hours=1), required=True, label='Duration', help_text="days hh:mm:ss", validators=[ MinValueValidator( datetime.timedelta(days=0, hours=1, minutes=0)) ]) time = forms.DateTimeField( label='Time', widget=forms.DateTimeInput(attrs={'type': 'datetime-local'}), validators=[MinValueValidator(timezone.localtime())]) num_weeks = forms.IntegerField( label='Repeat for(in weeks):', required=True, initial=1, help_text='1 for one time lectures, max 14', validators=[MaxValueValidator(14), MinValueValidator(1)]) class Meta: model = Lecture fields = ('time', 'duration', 'Class', 'num_weeks')
class PodcastUploadForm(Form): # title, duration, audio_file, album_name, tag1, tag2, tag3 title = forms.CharField(max_length=100) duration = forms.DurationField() audio_file = forms.FileField() tags = forms.CharField(max_length=40) album_name = forms.CharField(max_length=250)
class StepForm(ModelForm): description = forms.CharField(required=False) duration = forms.DurationField(required=False) class Meta: model = Step fields = ['prev', 'title', 'description', 'duration', 'ingredient', 'amount']
class RunInputForm(forms.ModelForm): distance = forms.FloatField(label=_("Distance (km)"), widget=forms.TextInput(), localize=True) start_date = forms.DateField( label=_("Run date"), widget=forms.DateInput(attrs={ 'id': 'start_datepicker', 'autocomplete': "off" })) end_date = forms.DateField(label=_("End date (if entering multiple runs)"), required=False, widget=forms.DateInput(attrs={ 'id': 'end_datepicker', 'autocomplete': "off" })) recorded_time = forms.DurationField(label=_("Time (HH:MM:SS, optional)"), required=False) class Meta: model = Run fields = ['distance', 'start_date', 'end_date', 'recorded_time'] def is_valid(self): valid = super(RunInputForm, self).is_valid() if not valid: return valid if self.cleaned_data['distance'] < 0: self.add_error('distance', 'Distance cannot be negative') valid = False return valid
class BaseRunForm(forms.Form): summary = forms.CharField(max_length=255) manager = UserField() default_tester = UserField(required=False) estimated_time = forms.DurationField(required=False) build = forms.ModelChoiceField(queryset=Build.objects.none(), ) notes = forms.CharField( widget=forms.Textarea, required=False, ) def populate(self, product_id): # We can dynamically set choices for a form field: # Seen at: http://my.opera.com/jacob7908/blog/2009/06/19/ # django-choicefield-queryset (Chinese) # Is this documented elsewhere? query = {'product_id': product_id} self.fields['build'].queryset = Build.list_active(query) def clean_estimated_time(self): estimated_time = self.cleaned_data.get('estimated_time', timedelta(0)) # can be either None, '', 0 or timedelta(0) if not estimated_time: estimated_time = timedelta(0) return estimated_time
class TaskForm(forms.Form): task_type = forms.CharField( widget=forms.TextInput({ "class": "form-control", 'placeholder': 'Task\'s name' })) nb_workers = forms.IntegerField( widget=forms.NumberInput({ "class": "form-control input-sm", 'placeholder': 'ppl needed' })) start = forms.CharField(widget=forms.TextInput({ "class": "form-control input-sm date_time", 'placeholder': 'Start' })) duration = forms.DurationField( widget=forms.TextInput({ "class": "form-control input-sm time", 'placeholder': 'Duration' })) difficulty = forms.IntegerField( widget=forms.NumberInput({ "class": "form-control input-md", 'placeholder': 'Difficulty' })) each_days = forms.BooleanField(required=False, initial=False)
class PlantForm(forms.Form): name = forms.CharField(label='Plant name (eg. Carlitos)', max_length=100) ptype = forms.CharField(label='Plant type (eg. Snake Plant)', max_length=100) location = forms.CharField(label='Plant location (eg. kitchen)', max_length=100) wtime = forms.DurationField(label='Watering duration (hr : min : sec)', initial=datetime.timedelta(minutes=2)) schedule_freq = forms.ChoiceField(label='Water this plant every', required=True, choices=FREQ) schedule_time = forms.ChoiceField(label='At', required=True, choices=TIME) schedule_start = forms.ChoiceField( label='On (only if watering every week)', required=True, choices=START) fnotif = forms.BooleanField( label='Notifications when the water reservoir is low', initial=True, required=False ) # Notification enable for when the water reservior needs to be refilled wnotif = forms.BooleanField( label='Notifications when the plant is watered', initial=True, required=False) # Notification enable for when the plant is watered def clean_name(self): name = self.cleaned_data.get('name') if Plant.objects.filter(name=name).exists(): raise forms.ValidationError( u'There is already a plant named "%s"' % name) return name
class MyForm(forms.Form): name = forms.CharField( label="User name", initial="User name", error_messages={'required': 'Please enter your' ' available email'}) profile_picture = forms.ImageField(widget=forms.FileInput) additional_file = forms.FileField(widget=forms.FileInput) email = forms.EmailField( initial="*****@*****.**", error_messages={'required': 'Please enter your available email'}) password = forms.CharField(max_length=20, min_length=10, required=False, widget=forms.PasswordInput()) age = forms.IntegerField(required=False, initial="45", help_text="Enter your current age") agreement = forms.BooleanField(required=False) average_score = forms.FloatField(initial=10.1) birthday = forms.DateField(widget=forms.SelectDateWidget, required=False) work_experience = forms.DurationField( required=False, widget=TimeDurationWidget(show_days=False)) gender = forms.ChoiceField(required=False, choices=[("1", "man"), ("2", "woman")])
class RecipeForm(forms.ModelForm): prep = forms.DurationField(widget=TimeDurationWidget(show_days=False, show_hours=True, show_minutes=True, show_seconds=False), required=False) cook = forms.DurationField(widget=TimeDurationWidget(show_days=False, show_hours=True, show_minutes=True, show_seconds=False), required=False) class Meta: model = Recipe fields = '__all__' exclude = ('author', )
class AddResultForm(forms.Form): result = forms.DurationField() medal = forms.BooleanField(required=False) def __init__(self, data=None, *args, **kwargs): """ Allows user to enter duration in HH:MM format instead of default HH:MM:SS format. In case user uses different symbol for ":" , the result can still be valid. In case user misses ":" entirely, the result can still be valid. """ if data: data = data.copy() data['result'] = data['result'].strip() if result_pattern[0].match(data['result']): data['result'] = data['result'][0:2] + ":" + data['result'][ 3:] + ":00" elif result_pattern[1].match(data['result']): data['result'] = data['result'][0:2] + ":" + data['result'][ 2:] + ":00" elif result_pattern[2].match(data['result']): data['result'] = '0' + data['result'][0] + ":" + data[ 'result'][2:] + ":00" elif result_pattern[3].match(data['result']): data['result'] = '0' + data['result'][0] + ":" + data[ 'result'][1:] + ":00" super().__init__(data, *args, **kwargs)
class ReportForm(forms.Form): class Media: js = () class Meta: model = Report name = forms.CharField(max_length=200, label='Имя отчёта') # Дампы, на которых основан отчёт dump = forms.ModelMultipleChoiceField(queryset=Dump.objects.all(), label='Дампы, по которым составлен отчёт') timeStart = forms.DateField( widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss", "pickSeconds": "true", "showTodayButton": "true"}), label='Начало атаки') timeEnd = forms.DateField( widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss", "pickSeconds": "true", "showTodayButton": "true"}), label='Конец атаки') # Продолжительность атаки duration = forms.DurationField(required=False, label='Продолжительность атаки') # Общее количество атак (пакетов) count = forms.IntegerField(required=False, label='Общее количество атак') # Количество уникальных IP uniqueIP = forms.IntegerField(required=False, label='Количество уникальных IP') # Основные страны-участники атаки countries = forms.CharField(max_length=200, label='Основные страны-источники') # Предполагаемая результативность result = forms.CharField(max_length=200, label='Предполагаемая результативность') # Предполагаемые управляющие центры controlCenters = forms.CharField(max_length=200, label='Предполагаемые управляющие центры')
class FilterAlertsForm(forms.Form): """Form for filtering a table of alerts Fields: include_internal (``BooleanField``) min_ra (``FloatField``) max_ra (``FloatField``) min_dec (``FloatField``) max_dec (``FloatField``)` time_range (``DurationField``) """ time_range = forms.DurationField(required=False, label='Publication time') min_ra = forms.FloatField(required=False, label='Min RA', widget=forms.TextInput()) max_ra = forms.FloatField(required=False, label='Max RA', widget=forms.TextInput()) min_dec = forms.FloatField(required=False, label='Min Dec', widget=forms.TextInput()) max_dec = forms.FloatField(required=False, label='Max Dec', widget=forms.TextInput()) include_internal = forms.BooleanField( required=False, label='Include internal status messages')
class ShowingCreateForm(ModelForm): start_time = forms.DateTimeField(input_formats=[ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%dT%H:%M', # '2006-10-25 14:30' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y' ] # '10/25/06' ) duration = forms.DurationField() def __init__(self, listingMLS, *args, **kwargs): # need to take listingMLS super().__init__(*args, **kwargs) self.listingMLS = listingMLS class Meta: model = Showing fields = ['start_time', 'duration'] def clean(self): cleaned_data = super().clean() start = cleaned_data.get('start_time') dur = cleaned_data.get('duration') if not is_showing_td_available(self.listingMLS, start, dur): raise ValidationError( ("Listing already booked for showing at that time."), code='overlap') return cleaned_data
class ServiceCreateForm(forms.ModelForm): def __init__(self, enterprise, *args, **kwargs): super(ServiceCreateForm, self).__init__(*args, **kwargs) self.fields['service'].queryset = Category.objects.filter( enterprise=enterprise) title = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='Услуга') service_desc = forms.CharField( widget=forms.Textarea(attrs={'class': 'form-control'}), label='Короткое описание') service_duration = forms.DurationField(widget=forms.TimeInput( attrs={'class': 'timepicker'})) min_price = forms.IntegerField( widget=forms.NumberInput(attrs={'class': 'form-control'}), label='Минимальная цена') max_price = forms.IntegerField( widget=forms.NumberInput(attrs={'class': 'form-control'}), label='Максимальная цена') access = forms.BooleanField(widget=forms.CheckboxInput, label='Доступен для записи') class Meta: model = Service fields = ('title', 'service_desc', 'service_duration', 'min_price', 'max_price', 'access', 'service')
class TaskModelForm(forms.ModelForm): deadline = forms.DateTimeField( required=False, input_formats=['%d/%m/%Y %H:%M', '%d/%m/%Y %H:%M:%S'], widget=XDSoftDateTimePickerInput()) start = forms.DateTimeField( required=False, input_formats=['%d/%m/%Y %H:%M', '%d/%m/%Y %H:%M:%S'], widget=XDSoftDateTimePickerInput()) duration = forms.DurationField( required=False, widget=MyDurationWidget(), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs.update(size='45', autofocus=True) class Meta: model = models.Task fields = ( 'title', 'details', 'category', 'place', 'start', 'deadline', 'duration', 'importance', 'priority', 'status', )
class StepForm(ModelForm): description = forms.CharField(required=False) duration = forms.DurationField(required=False) class Meta: model = Step fields = [ 'prev', 'title', 'description', 'duration', 'ingredient', 'amount', 'unit' ] def clean(self): ingredient = self.cleaned_data.get('ingredient', None) amount = self.cleaned_data.get('amount', None) unit = self.cleaned_data.get('unit', None) if ingredient and not amount: self.errors['amount'] = self.error_class( ['Mengenangabe wird benötigt!']) if amount and not ingredient: self.errors['ingredient'] = self.error_class( ['Zutat muss gewählt werden.']) if amount and not unit: self.errors['unit'] = self.error_class(['Einheit wird benötigt!']) return self.cleaned_data
class AppointmentForm(forms.Form): name = forms.CharField(max_length=100) breed = forms.CharField(max_length=100) notes = forms.CharField(label='Special notes', widget=forms.Textarea) date = forms.DateField(widget=forms.SelectDateWidget) start_time = forms.TimeField() duration = forms.DurationField() age = forms.IntegerField()
class UserRecordForm(forms.ModelForm): time_start = forms.DateTimeField() time_end = forms.DateTimeField() time_productive = forms.DurationField() class Meta: model = models.UserRecord fields = ("time_start", "time_end", "time_productive")
class AddResultForm(forms.Form): event = forms.ModelChoiceField(queryset=Event.objects.all()) time = forms.DurationField( label='Time', widget=forms.TextInput(attrs={'placeholder': '00:00.00'})) date = forms.DateField( label='Date', widget=forms.TextInput(attrs={'placeholder': 'YYYY-MM-DD'}))
class CalendrierColleurForm(forms.Form): colle = forms.ModelChoiceField(queryset=None, required=False, widget=forms.TextInput, disabled=True) debut = ISODateTimeField() duree = forms.DurationField() duree_etudiant = forms.DurationField(required=False) def __init__(self, *args, **kwargs): self.colleur = kwargs.pop('colleur') self.enseignement = kwargs.pop('enseignement') super().__init__(*args, **kwargs) self.fields['colle'].queryset = Colle.objects.filter( colledetails__actif=True, colledetails__colleur=self.colleur, enseignement=self.enseignement)