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 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")])
def __init__(self, *args, **kwargs): super(IngredientAdminForm, self).__init__(*args, **kwargs) self.fields['conservation_day'].widget = TimeDurationWidget( show_days=True, show_hours=False, show_minutes=False, show_seconds=False)
class MonsterForm(forms.ModelForm): image = forms.ClearableFileInput() default_time = forms.DurationField(widget=TimeDurationWidget(), required=True, initial=settings.INITIAL_DEFAULT_TIME, ) advanced_time = forms.DurationField(widget=TimeDurationWidget(), required=True, initial=settings.INITIAL_ADVANCED_TIME, ) class Meta: model = Monster fields = ['name', 'monster_type', 'image', 'default_time', 'advanced_time', 'currency', 'buy_cost', 'sell_cost', 'how_to_breed']
class timerForm(forms.Form): screen_name = forms.CharField(label='Screen name', max_length=10) duration = forms.DurationField(label='Display duration:', initial="00:05:00", widget=TimeDurationWidget( show_days=False, show_hours=True, show_minutes=True, show_seconds=False)) delay = forms.DurationField(label='Show in... (/delay)', initial="00:00:00", widget=TimeDurationWidget(show_days=False, show_hours=True, show_minutes=True, show_seconds=False)) message = forms.CharField(label='Display text:', max_length=20) templates = forms.ChoiceField(choices=[ (templ.pk, templ.name) for templ in Template.objects.all() ], label="Template")
class alarmForm(forms.Form): screen_name = forms.CharField(label='Your name', max_length=10) duration = forms.DurationField(label='Display duration:', initial="00:05:00", widget=TimeDurationWidget( show_days=False, show_hours=True, show_minutes=True, show_seconds=False)) start_at = forms.DateTimeField(label="Start date", initial=timezone.now(), widget=DateTimeInput) message = forms.CharField( label='Display text:', max_length=20, ) templates = forms.ChoiceField(choices=[ (templ.pk, templ.name) for templ in Template.objects.all() ], label="Template")
class Meta: model = Doctor fields = [ 'name', 'email', 'credentials', 'languages', 'notify', 'notify_interval', 'quiet_time_start', 'quiet_time_end', 'utc_offset', 'fcm_token', 'self_certification_questions', 'remarks' ] widgets = { 'languages': CheckboxSelectMultiple(), 'notify_interval': TimeDurationWidget(show_days=False, show_minutes=False, show_seconds=False), 'quiet_time_start': TimeInput(), 'quiet_time_end': TimeInput(), 'self_certification_questions': CheckboxSelectMultiple(), }
class TaskForm(ModelForm): model = Task duration = DurationField(widget=TimeDurationWidget(show_days=True, show_hours=True, show_minutes=True, show_seconds=False), required=False) start_date = CharField(widget=TextInput(attrs={'type': 'date'})) end_date = CharField(widget=TextInput(attrs={'type': 'date'})) def __init__(self, *args, **kwargs): user = kwargs.pop('user') super().__init__(*args, **kwargs) instance = getattr(self, 'instance', None) # tags self.fields['tags'].widget.attrs['multiple'] = 'multiple' self.fields['tags'].widget.attrs['class'] = "selectpicker" self.fields['tags'].queryset = user.tags.all() l_tags_dict = OrderedDict() tags_in_project = [] if instance.pk: tags_in_project = instance.tags.all() for t in tags_in_project: try: l_tags_dict['in the project'].append((t.pk, t.name)) except KeyError: l_tags_dict['in the project'] = [(t.pk, t.name)] for t in set(instance.refer_client.tags.all()).difference( tags_in_project): try: l_tags_dict['not yet in the project'].append( (t.pk, t.name)) except KeyError: l_tags_dict['not yet in the project'] = [(t.pk, t.name)] self.fields['tags'].choices = l_tags_dict.items() else: self.fields['tags'].queryset = user.tags.all() # users self.fields['users'].widget.attrs['multiple'] = 'multiple' self.fields['users'].widget.attrs['class'] = "selectpicker" l_users_dict = OrderedDict() users_in_project = [] if instance.pk: users_in_project = instance.users.all() for u in users_in_project: try: l_users_dict['in the project'].append((u.pk, u.name)) except KeyError: l_users_dict['in the project'] = [(u.pk, u.name)] for u in set(instance.refer_client.users.all()).difference( users_in_project): try: l_users_dict['not yet in the project'].append( (u.pk, u.name)) except KeyError: l_users_dict['not yet in the project'] = [(u.pk, u.name)] self.fields['users'].choices = l_users_dict.items() else: self.fields['users'].queryset = user.users.all() self.fields['refer_client'].widget.attrs['class'] = "selectpicker" self.fields['refer_client'].queryset = user.clients.all() self.fields['refer_project'].widget.attrs['class'] = "selectpicker" self.fields['refer_project'].queryset = user.projects.all() self.fields['duration'].widget.attrs[ 'class'] = "form-control timeduration" self.fields['description'].widget = Textarea(attrs={ 'cols': 80, 'rows': 4 }) class Meta: model = Task fields = [ 'name', 'description', 'refer_client', 'refer_project', 'users', 'tags', 'duration', 'start_date', 'end_date', 'done' ]
class HourSlotForm(BaseFormWithHourSlotsGroupCheck): starts_at = forms.TimeField( input_formats=['%H:%M'], widget=forms.TextInput(attrs={'class': 'form-control timepicker'})) ends_at = forms.TimeField( input_formats=['%H:%M'], widget=forms.TextInput(attrs={'class': 'form-control timepicker'})) legal_duration = forms.DurationField(widget=TimeDurationWidget( show_days=False, show_hours=True, show_minutes=True, show_seconds=False, attrs={'class': 'form-control duration-input'}), required=False) def __init__(self, user, *args, **kwargs): super(HourSlotForm, self).__init__(user, *args, **kwargs) assign_html_style_to_visible_forms_fields(self) class Meta: model = HourSlot fields = [ 'hour_number', 'starts_at', 'ends_at', 'hour_slots_group', 'day_of_week', 'legal_duration' ] def check_conflict_on_day(self, day_of_week): # Check if there is already the n-th hour of the day: conflicting_hour_number = HourSlot.objects.filter( hour_slots_group=self.cleaned_data['hour_slots_group'], day_of_week=day_of_week, hour_number=self.cleaned_data['hour_number']) if conflicting_hour_number.exists(): if self.instance is not None and conflicting_hour_number.first( ).pk != self.instance.id: self.add_error( None, forms.ValidationError( _("There is already the {}{} hour of the day " "for this school, day of week and school_year!". format( self.cleaned_data['hour_number'], _("th") if self.cleaned_data['hour_number'] % 10 > 3 else _("st") if self.cleaned_data['hour_number'] % 10 == 1 else _("nd") if self.cleaned_data['hour_number'] % 10 == 2 else _("rd"))))) # TODO: add tests for this check! conflicting_time_interval = HourSlot.objects.filter( hour_slots_group=self.cleaned_data['hour_slots_group'], day_of_week=day_of_week ).filter( # Conflicting interval is when the start of the new interval is above the end of an existing one, # and the end is before the start of the existing one. Q(starts_at__lt=self.cleaned_data['ends_at']) & Q(ends_at__gt=self.cleaned_data['starts_at'])) if conflicting_time_interval.exists(): if self.instance is None: # We are creating the hour slot, and we already have one in the same time interval. self.add_error( None, forms.ValidationError( "You cannot create an hour slot in this time interval," " since there is already one on {} from {} to {}". format( models.DAYS_OF_WEEK[conflicting_time_interval. first().day_of_week][1], conflicting_time_interval.first().starts_at, conflicting_time_interval.first().ends_at))) elif conflicting_time_interval.count() > 1 or \ conflicting_time_interval.first().pk != self.instance.pk: # We are editing an existing hour slot, but there is an hour slot which is not the current one # in the same time interval. self.add_error( None, forms.ValidationError( "You cannot create an hour slot in this time interval," " since there is already one on {} from {} to {}". format( models.DAYS_OF_WEEK[conflicting_time_interval. first().day_of_week][1], conflicting_time_interval.first().starts_at, conflicting_time_interval.first().ends_at))) def clean(self): """ Of course, the starts_at must be smaller than ends_at. Moreover, we cannot have another hour-slot with the same hour_number in the same day, school and school_year. Lastly, no hour slot can be held in the same interval of another existing one, the same day. :return: """ if self.cleaned_data['starts_at'] >= self.cleaned_data['ends_at']: self.add_error( None, forms.ValidationError( _('The start hour must be strictly smaller that the ' 'end hour.'))) if 'hour_slots_group' in self.cleaned_data: # If hour_slots_group is not a key, clean_hour_slots_group has already failed. self.check_conflict_on_day(self.cleaned_data['day_of_week']) return self.cleaned_data
class DurationFieldFormMixin(forms.ModelForm): period = forms.DurationField( label="Период диагностики", widget=TimeDurationWidget(show_days=True, show_hours=False, show_minutes=False, show_seconds=False), required=False )
class CustomerAgreementAdminForm(forms.ModelForm): """ Helps convert the unuseful database value, stored in microseconds, of ``license_duration_before_purge`` to a useful value, and vica versa. """ # Hide this field when creating a new CustomerAgreement subscription_for_auto_applied_licenses = forms.ChoiceField( required=False, widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'instance' in kwargs: instance = kwargs['instance'] if instance: self.populate_subscription_for_auto_applied_licenses_choices( instance) def populate_subscription_for_auto_applied_licenses_choices( self, instance): """ Populates the choice field used to choose which plan is used for auto-applied licenses in a Customer Agreement. """ now = localized_utcnow() active_plans = SubscriptionPlan.objects.filter( customer_agreement=instance, is_active=True, start_date__lte=now, expiration_date__gte=now) current_plan = instance.auto_applicable_subscription empty_choice = ('', '------') choices = [empty_choice] + [(plan.uuid, plan.title) for plan in active_plans] choice_field = forms.ChoiceField( choices=choices, required=False, initial=empty_choice if not current_plan else (current_plan.uuid, current_plan.title)) self.fields['subscription_for_auto_applied_licenses'] = choice_field def _validate_enterprise_customer_uuid(self): """ Verifies that a customer with the given enterprise_customer_uuid exists """ enterprise_customer_uuid = self.instance.enterprise_customer_uuid try: customer_data = EnterpriseApiClient().get_enterprise_customer_data( enterprise_customer_uuid) self.instance.enterprise_customer_slug = customer_data.get('slug') self.instance.enterprise_customer_name = customer_data.get('name') return True except HTTPError as ex: logger.exception( f'Could not validate enterprise_customer_uuid {enterprise_customer_uuid}.' ) if ex.response.status_code == status.HTTP_404_NOT_FOUND: self.add_error( 'enterprise_customer_uuid', f'An enterprise customer with uuid: {enterprise_customer_uuid} does not exist.', ) else: self.add_error( 'enterprise_customer_uuid', f'Could not verify the given UUID: {ex}. Please try again.', ) return False def _validate_default_enterprise_catalog_uuid(self): """ Verifies that the enterprise customer has a catalog with the given default_enterprise_catalog_uuid. """ default_enterprise_catalog_uuid = self.instance.default_enterprise_catalog_uuid if not default_enterprise_catalog_uuid: return True try: catalog = EnterpriseCatalogApiClient().get_enterprise_catalog( default_enterprise_catalog_uuid) catalog_enterprise_customer_uuid = catalog['enterprise_customer'] if str(self.instance.enterprise_customer_uuid ) != catalog_enterprise_customer_uuid: self.add_error( 'default_enterprise_catalog_uuid', 'A catalog with the given UUID does not exist for this enterprise customer.', ) return False return True except HTTPError as ex: logger.exception( f'Could not validate default_enterprise_catalog_uuid {default_enterprise_catalog_uuid}.' ) if ex.response.status_code == status.HTTP_404_NOT_FOUND: self.add_error( 'default_enterprise_catalog_uuid', 'A catalog with the given UUID does not exist for this enterprise customer.', ) else: self.add_error( 'default_enterprise_catalog_uuid', f'Could not verify the given UUID: {ex}. Please try again.', ) return False def is_valid(self): # Perform original validation and return if false if not super().is_valid(): return False if settings.VALIDATE_FORM_EXTERNAL_FIELDS: if not all([ self._validate_enterprise_customer_uuid(), self._validate_default_enterprise_catalog_uuid() ]): return False return True class Meta: model = CustomerAgreement fields = '__all__' license_duration_before_purge = forms.DurationField( widget=TimeDurationWidget( show_days=True, show_hours=False, show_minutes=False, show_seconds=False, ), help_text= _("The number of days after which unclaimed, revoked, or expired (due to plan expiration) licenses " "associated with this customer agreement will have user data retired " "and the license status reset to UNASSIGNED."), )