class Meta(ModelForm): model = Account fields = ['account_name', 'account_type', 'starting_balance'] widgets = { 'account_type': Select(attrs={'style': 'display: block;'}), }
class BGFinProdRegForm(Form): issuer_full_name = CharField(required=False) issuer_short_name = CharField(required=False) issuer_legal_address = CharField(required=False) issuer_ogrn = CharField(required=False) issuer_inn = CharField(required=False) issuer_kpp = CharField(required=False) tender_gos_number = CharField(required=False) tender_placement_type = CharField(required=False) tender_exec_law = ChoiceField( required=False, choices=[ (consts.TENDER_EXEC_LAW_44_FZ, '44-ФЗ'), (consts.TENDER_EXEC_LAW_223_FZ, '223-ФЗ'), (consts.TENDER_EXEC_LAW_185_FZ, '185-ФЗ'), (consts.TENDER_EXEC_LAW_COMMERCIAL, 'Коммерческий'), (consts.TENDER_EXEC_LAW_CUSTOMS, 'Таможенная'), (consts.TENDER_EXEC_LAW_VAT, 'Возврат НДС'), ]) tender_publish_date = DateField(required=False) tender_start_cost = DecimalField(decimal_places=2, required=False, localize=True) tender_final_cost = DecimalField(decimal_places=2, required=False, localize=True) tender_responsible_full_name = CharField(required=False) tender_responsible_legal_address = CharField(required=False) tender_responsible_inn = CharField(required=False) tender_responsible_kpp = CharField(required=False) tender_responsible_ogrn = CharField(required=False) bg_commercial_contract_subject = CharField(required=False) bg_commercial_contract_place_of_work = CharField(required=False) bg_commercial_contract_sum = DecimalField(decimal_places=2, required=False, localize=True) bg_commercial_contract_sign_date = DateField(required=False) bg_commercial_contract_end_date = DateField(required=False) balance_code_2400_offset_1 = BalanceCodeDecimalField(decimal_places=2, required=False, localize=True) balance_code_2400_offset_0 = BalanceCodeDecimalField(decimal_places=2, required=False, localize=True) bg_sum = DecimalForcedThousandsGroupedField(decimal_places=2, required=False, localize=True) bg_currency = ChoiceField(required=False, choices=[ (consts.CURRENCY_RUR, 'Рубль'), (consts.CURRENCY_USD, 'Доллар'), (consts.CURRENCY_EUR, 'Евро'), ]) bg_start_date = DateField(required=False) bg_end_date = DateField(required=False) bg_deadline_date = DateField(required=False) bg_type = ChoiceField( required=False, choices=[ (consts.BG_TYPE_APPLICATION_ENSURE, 'Обеспечение заявки'), (consts.BG_TYPE_CONTRACT_EXECUTION, 'Исполнение контракта'), (consts.BG_TYPE_REFUND_OF_ADVANCE, 'Возврат аванса'), (consts.BG_TYPE_WARRANTY_ENSURE, 'Обеспечение гарантийных обязательств'), ]) bg_is_benefeciary_form = BooleanField(required=False, widget=Select( attrs={'class': 'form-control'}, choices=[ (True, 'Да'), (False, 'Нет'), ])) is_indisputable_charge_off = BooleanField( required=False, initial=True, widget=Select(attrs={'class': 'form-control'})) tender_contract_type = ChoiceField( required=False, choices=[ (consts.TENDER_CONTRACT_TYPE_SUPPLY_CONTRACT, 'Поставка товара'), (consts.TENDER_CONTRACT_TYPE_SERVICE_CONTRACT, 'Оказание услуг'), (consts.TENDER_CONTRACT_TYPE_WORKS_CONTRACT, 'Выполнение работ'), ]) tender_contract_subject = CharField(widget=Textarea(), required=False) stop_factors = Field(required=False) tender_has_prepayment = BooleanField(required=False) already_has_an_agent = Field(required=False) def clean(self): bg_sum_min = BankMinimalCommission.objects.order_by( 'sum_min').first().sum_min bg_sum_max = BankMinimalCommission.objects.order_by( '-sum_max').first().sum_max if not self.cleaned_data[ 'bg_sum'] or not bg_sum_min < self.cleaned_data[ 'bg_sum'] < bg_sum_max: self.add_error(None, 'Неверная сумма запрашиваемой гарантии') bg_start = self.cleaned_data['bg_start_date'] bg_end = self.cleaned_data['bg_end_date'] if bg_end and bg_start: bg_months_diff = 1 + (bg_end.year - bg_start.year ) * 12 + bg_end.month - bg_start.month else: bg_months_diff = 0 if not bg_start or not bg_end or not 0 < bg_months_diff < 30: self.add_error(None, 'Неверный срок действия запрашиваемой гарантии') balance_code_2400_offset_0 = self.cleaned_data[ 'balance_code_2400_offset_0'] balance_code_2400_offset_1 = self.cleaned_data[ 'balance_code_2400_offset_1'] if balance_code_2400_offset_0 < 0 or balance_code_2400_offset_1 < 0: self.add_error(None, 'Отрицательная прибыль')
class BGFinProdSurveyDealParamsForm(Form): bg_is_benefeciary_form = BooleanField(required=False, widget=Select( attrs={'class': 'form-control'}, choices=[ (True, 'Да'), (False, 'Нет'), ])) is_indisputable_charge_off = BooleanField( required=False, widget=Select(attrs={'class': 'form-control'}, choices=[ (True, 'Да'), (False, 'Нет'), ])) tender_contract_subject = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) deal_has_beneficiary = ChoiceField( required=False, widget=Select(attrs={'class': 'form-control'}), choices=[ (True, 'Присутствует'), (False, 'Отсутствует'), ]) issuer_bank_relations_term = ChoiceField( required=False, widget=Select(attrs={'class': 'form-control'}), choices=[ (consts.ISSUE_DEAL_BANK_RELATIONS_TERM_SHORT, 'Краткосрочные'), (consts.ISSUE_DEAL_BANK_RELATIONS_TERM_LONG, 'Долгосрочные'), ]) issuer_activity_objective = ChoiceField( required=False, widget=Select(attrs={'class': 'form-control'}), choices=[ (consts.ISSUE_ISSUER_ACTIVITY_OBJECTIVE_PROFIT_MAKING, 'Получение прибыли'), (consts.ISSUE_ISSUER_ACTIVITY_OBJECTIVE_OTHER, 'Иное'), ]) issuer_finance_situation = ChoiceField( required=False, widget=Select(attrs={'class': 'form-control'}), choices=[ (consts.ISSUE_ISSUER_FINANCE_SITUATION_SATISFIED, 'Удовлетворительное'), (consts.ISSUE_ISSUER_FINANCE_SITUATION_UNSATISFIED, 'Неудовлетворительное'), ]) issuer_business_reputation = ChoiceField( required=False, widget=Select(attrs={'class': 'form-control'}), choices=[ (consts.ISSUE_ISSUER_BUSINESS_REPUTATION_POSITIVE, 'Положительная'), (consts.ISSUE_ISSUER_BUSINESS_REPUTATION_NOT_PRESENT, 'Отсутствует'), ]) issuer_funds_source = ChoiceField( required=False, widget=Select(attrs={'class': 'form-control'}), choices=[ (consts.ISSUER_FUNDS_SOURCE_LOAN_FUNDS, 'Заемные средства'), (consts.ISSUER_FUNDS_SOURCE_OTHER, 'Иное'), ])
class GastroSubmitForm(ModelForm): opening_mon = TimeField(required=False) opening_tue = TimeField(required=False) opening_wed = TimeField(required=False) opening_thu = TimeField(required=False) opening_fri = TimeField(required=False) opening_sat = TimeField(required=False) opening_sun = TimeField(required=False) closing_mon = TimeField(required=False) closing_tue = TimeField(required=False) closing_wed = TimeField(required=False) closing_thu = TimeField(required=False) closing_fri = TimeField(required=False) closing_sat = TimeField(required=False) closing_sun = TimeField(required=False) delivery = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) organic = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) handicapped_accessible = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) handicapped_accessible_wc = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) dog = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) child_chair = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) catering = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) wlan = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) gluten_free = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) breakfast = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) brunch = NullBooleanField( widget=Select(choices=NULLBOOLEAN_CHOICE), initial=NULLBOOLEAN_NULL, required=False, ) restaurant = BooleanField(initial=False, required=False) imbiss = BooleanField(initial=False, required=False) eiscafe = BooleanField(initial=False, required=False) cafe = BooleanField(initial=False, required=False) bar = BooleanField(initial=False, required=False) seats_indoor = IntegerField(min_value=0, initial=0) seats_outdoor = IntegerField(min_value=0, initial=0) class Meta: model = BaseLocation fields = [ "name", "street", "postal_code", "city", "latitude", "longitude", "telephone", "website", "email", "opening_mon", "closing_mon", "opening_tue", "closing_tue", "opening_wed", "closing_wed", "opening_thu", "closing_thu", "opening_fri", "closing_fri", "opening_sat", "closing_sat", "opening_sun", "closing_sun", "vegan", "comment", "comment_english", "comment_opening_hours", "comment_public_transport", "handicapped_accessible", "handicapped_accessible_wc", "dog", "child_chair", "catering", "delivery", "organic", "wlan", "gluten_free", "breakfast", "brunch", "seats_outdoor", "seats_indoor", "restaurant", "imbiss", "eiscafe", "cafe", "bar", "submit_email", ] def __init__(self, *args, **kwargs): super(GastroSubmitForm, self).__init__(*args, **kwargs) self.fields["latitude"].widget = HiddenInput() self.fields["longitude"].widget = HiddenInput() self.fields["city"].widget.attrs["readonly"] = True self.fields["postal_code"].widget = NumberInput(attrs={"maxlength": 5}) open = [ "opening_mon", "opening_tue", "opening_wed", "opening_thu", "opening_fri", "opening_sat", "opening_sun", ] close = [ "closing_mon", "closing_tue", "closing_wed", "closing_thu", "closing_fri", "closing_sat", "closing_sun", ] # change label opening for o in open: self.fields[o].label = _("Opens at") self.fields[o].widget.attrs.update( {"data-picker": "timepicker-opens"}) # change label closing for c in close: self.fields[c].label = _("Closes at") self.fields[c].widget.attrs.update( {"data-picker": "timepicker-closes"}) # add timepicker and format hh:mm timepicker = open + close for t in timepicker: self.fields[t].widget.attrs.update({"placeholder": "HH:MM"}) self.fields[t].widget.format = "%H:%M" def save(self, commit=True): self.instance.type = LocationTypeChoices.GASTRO with transaction.atomic(): instance = super(GastroSubmitForm, self).save(commit=True) self._save_opening_hours(instance=instance) self._save_tags(instance=instance) self._save_attrs( instance=instance, attr_keys=dict(GASTRO_POSITIVE_INTEGER_ATTRIBUTE_CHOICES), attr_model=PositiveIntegerAttribute, attr_manager="positive_integer_attributes", ) self._save_attrs( instance=instance, attr_keys=dict(GASTRO_BOOLEAN_ATTRIBUTE_CHOICES), attr_model=BooleanAttribute, attr_manager="boolean_attributes", ) return instance def _save_opening_hours(self, instance: BaseLocation): OPENING_HOURS_PAIRS = { WeekdayChoices.MONDAY: ("opening_mon", "closing_mon"), WeekdayChoices.TUESDAY: ("opening_tue", "closing_tue"), WeekdayChoices.WEDNESDAY: ("opening_wed", "closing_wed"), WeekdayChoices.THURSDAY: ("opening_thu", "closing_thu"), WeekdayChoices.FRIDAY: ("opening_fri", "closing_fri"), WeekdayChoices.SATURDAY: ("opening_sat", "closing_sat"), WeekdayChoices.SUNDAY: ("opening_sun", "closing_sun"), } opening_hours = [] for day, day_keys in OPENING_HOURS_PAIRS.items(): opening_hours.append( OpeningHours( location=instance, weekday=day, opening=self.cleaned_data[day_keys[0]], closing=self.cleaned_data[day_keys[1]], )) OpeningHours.objects.bulk_create(opening_hours) def _save_tags(self, instance: BaseLocation): TAGS_SET = { "restaurant": "restaurant", "imbiss": "snack bar", "eiscafe": "ice cream parlor", "cafe": "cafe", "bar": "bar", } tags: List[Tag] = [] for form_field, tag_name in TAGS_SET.items(): tag = self.cleaned_data[form_field] if tag: tags.append(Tag.objects.get_or_create(tag=tag_name)[0]) instance.tags.set(tags) def _save_attrs( self, instance: BaseLocation, attr_keys: Dict[str, str], attr_model: Type[Union[PositiveIntegerAttribute, BooleanAttribute]], attr_manager: str, ): attrs: List[attr_model] = [] for attr_key in attr_keys: attr_value = self.cleaned_data[attr_key] attrs.append( attr_model.objects.get_or_create(name=attr_key, state=attr_value)[0]) getattr(instance, attr_manager).set(attrs)
def formfield_for_foreignkey(self, db_field, request, **kwargs): kwargs["widget"] = Select(attrs={'style': 'width: 250px;'}) if db_field.name == "url": kwargs["queryset"] = UrlModel.objects.order_by('comments') return super().formfield_for_foreignkey(db_field, request, **kwargs)
def __init__(self, *args, space_id=None, request=None, geometry_editable=False, is_json=False, **kwargs): self.request = request super().__init__(*args, **kwargs) creating = not self.instance.pk if hasattr(self.instance, 'author_id'): if self.instance.author_id is None: self.instance.author = request.user if 'geometry' in self.fields: if not geometry_editable: # can't see this geometry in editor self.fields.pop('geometry') else: # hide geometry widget self.fields['geometry'].widget = HiddenInput() if not creating: self.initial['geometry'] = json.dumps(mapping(self.instance.geometry), separators=(',', ':')) if self._meta.model.__name__ == 'Source' and self.request.user.is_superuser: Source = self.request.changeset.wrap_model('Source') sources = {s['name']: s for s in Source.objects.all().values('name', 'access_restriction_id', 'left', 'bottom', 'right', 'top')} used_names = set(sources.keys()) all_names = set(os.listdir(settings.SOURCES_ROOT)) if not creating: used_names.remove(self.instance.name) all_names.add(self.instance.name) self.fields['name'].widget = Select(choices=tuple((s, s) for s in sorted(all_names-used_names))) if creating: for s in sources.values(): s['access_restriction'] = s['access_restriction_id'] del s['access_restriction_id'] self.fields['copy_from'] = ChoiceField( choices=tuple((('', '---------'), ))+tuple( (json.dumps(sources[name], separators=(',', ':'), cls=DjangoJSONEncoder), name) for name in sorted(used_names) ), required=False ) self.fields['fixed_x'] = DecimalField(label='fixed x', required=False, max_digits=7, decimal_places=3, initial=0) self.fields['fixed_y'] = DecimalField(label='fixed y', required=False, max_digits=7, decimal_places=3, initial=0) self.fields['scale_x'] = DecimalField(label='scale x (m/px)', required=False, max_digits=7, decimal_places=3, initial=1) self.fields['scale_y'] = DecimalField(label='scale y (m/px)', required=False, max_digits=7, decimal_places=3, initial=1) self.fields['lock_aspect'] = BooleanField(label='lock aspect ratio', required=False, initial=True) self.fields['lock_scale'] = BooleanField(label='lock scale (for moving)', required=False, initial=True) self.fields.move_to_end('lock_scale', last=False) self.fields.move_to_end('lock_aspect', last=False) self.fields.move_to_end('scale_y', last=False) self.fields.move_to_end('scale_x', last=False) self.fields.move_to_end('fixed_y', last=False) self.fields.move_to_end('fixed_x', last=False) self.fields.move_to_end('access_restriction', last=False) if creating: self.fields.move_to_end('copy_from', last=False) self.fields.move_to_end('name', last=False) if self._meta.model.__name__ == 'AccessRestriction': AccessRestrictionGroup = self.request.changeset.wrap_model('AccessRestrictionGroup') self.fields['groups'].label_from_instance = lambda obj: obj.title self.fields['groups'].queryset = AccessRestrictionGroup.qs_for_request(self.request) elif 'groups' in self.fields: LocationGroupCategory = self.request.changeset.wrap_model('LocationGroupCategory') kwargs = {'allow_'+self._meta.model._meta.default_related_name: True} categories = LocationGroupCategory.objects.filter(**kwargs).prefetch_related('groups') if self.instance.pk: instance_groups = tuple(self.instance.groups.values_list('pk', flat=True)) else: instance_groups = () self.fields.pop('groups') for category in categories: choices = tuple((str(group.pk), group.title) for group in sorted(category.groups.all(), key=self.sort_group)) category_groups = set(group.pk for group in category.groups.all()) initial = tuple(str(pk) for pk in instance_groups if pk in category_groups) if category.single: name = 'group_'+category.name initial = initial[0] if initial else '' choices = (('', '---'), )+choices field = ChoiceField(label=category.title, required=False, initial=initial, choices=choices, help_text=category.help_text) else: name = 'groups_'+category.name field = MultipleChoiceField(label=category.title_plural, required=False, initial=initial, choices=choices, help_text=category.help_text) self.fields[name] = field if 'label_settings' in self.fields: self.fields.move_to_end('label_settings') for field in tuple(self.fields.keys()): if field.startswith('label_override'): self.fields.move_to_end(field) if 'category' in self.fields: self.fields['category'].label_from_instance = attrgetter('title') if 'label_settings' in self.fields: self.fields['label_settings'].label_from_instance = attrgetter('title') if 'access_restriction' in self.fields: AccessRestriction = self.request.changeset.wrap_model('AccessRestriction') self.fields['access_restriction'].label_from_instance = lambda obj: obj.title self.fields['access_restriction'].queryset = AccessRestriction.qs_for_request(self.request) if 'base_mapdata_accessible' in self.fields: if not request.user.is_superuser: self.fields['base_mapdata_accessible'].disabled = True if space_id and 'target_space' in self.fields: Space = self.request.changeset.wrap_model('Space') GraphNode = self.request.changeset.wrap_model('GraphNode') GraphEdge = self.request.changeset.wrap_model('GraphEdge') cache_key = 'editor:neighbor_spaces:%s:%s%d' % ( self.request.changeset.raw_cache_key_by_changes, AccessPermission.cache_key_for_request(request, with_update=False), space_id ) other_spaces = cache.get(cache_key, None) if other_spaces is None: AccessPermission.cache_key_for_request(request, with_update=False) + ':' + str(request.user.pk or 0) space_nodes = set(GraphNode.objects.filter(space_id=space_id).values_list('pk', flat=True)) space_edges = GraphEdge.objects.filter( Q(from_node_id__in=space_nodes) | Q(to_node_id__in=space_nodes) ).values_list('from_node_id', 'to_node_id') other_nodes = set(chain(*space_edges)) - space_nodes other_spaces = set(GraphNode.objects.filter(pk__in=other_nodes).values_list('space_id', flat=True)) other_spaces.discard(space_id) cache.set(cache_key, other_spaces, 900) for space_field in ('origin_space', 'target_space'): other_space_id = getattr(self.instance, space_field+'_id', None) if other_space_id: other_spaces.add(other_space_id) space_qs = Space.qs_for_request(self.request).filter(pk__in=other_spaces) for space_field in ('origin_space', 'target_space'): if space_field in self.fields: self.fields[space_field].label_from_instance = lambda obj: obj.title self.fields[space_field].queryset = space_qs self.redirect_slugs = None self.add_redirect_slugs = None self.remove_redirect_slugs = None if 'slug' in self.fields: self.redirect_slugs = sorted(self.instance.redirects.values_list('slug', flat=True)) self.fields['redirect_slugs'] = CharField(label=_('Redirecting Slugs (comma separated)'), required=False, initial=','.join(self.redirect_slugs)) self.fields.move_to_end('redirect_slugs', last=False) self.fields.move_to_end('slug', last=False) if 'from_node' in self.fields: self.fields['from_node'].widget = HiddenInput() if 'to_node' in self.fields: self.fields['to_node'].widget = HiddenInput() if 'data' in self.fields and 'data' in self.initial: self.initial['data'] = json.dumps(self.initial['data']) self.is_json = is_json self.missing_fields = tuple((name, field) for name, field in self.fields.items() if name not in self.data and not field.required)
def formfield_for_dbfield(self, db_field, request, **kwargs): if db_field.name == "machine_type": kwargs["widget"] = Select() return super().formfield_for_dbfield(db_field, request, **kwargs)
class HighPotentialOpportunityForm(forms.Form): action_class = GovNotifyAction COMPANY_SIZE_CHOICES = [ ('1 - 10', '1 - 10'), ('11 - 50', '11 - 50'), ('51 - 250', '51 - 250'), ('250+', '250+'), ] def __init__(self, field_attributes, opportunity_choices, *args, **kwargs): for field_name, field in self.base_fields.items(): attributes = field_attributes.get(field_name) if attributes: field.__dict__.update(attributes) self.base_fields['opportunities'].choices = opportunity_choices return super().__init__(*args, **kwargs) full_name = fields.CharField() role_in_company = fields.CharField() email_address = fields.EmailField() phone_number = fields.CharField() company_name = fields.CharField() website_url = fields.CharField(required=False) country = fields.ChoiceField( choices=[('', 'Please select')] + choices.COUNTRY_CHOICES, widget=Select(attrs={'id': 'js-country-select'}), ) company_size = fields.ChoiceField(choices=COMPANY_SIZE_CHOICES) opportunities = fields.MultipleChoiceField( widget=widgets.CheckboxSelectInlineLabelMultiple( attrs={'id': 'checkbox-multiple'}, use_nice_ids=True, ), choices=[] # set in __init__ ) comment = fields.CharField(widget=Textarea, required=False) terms_agreed = fields.BooleanField(label=mark_safe( 'Tick this box to accept the ' f'<a href="{urls.TERMS_AND_CONDITIONS}" target="_blank">terms and ' 'conditions</a> of the great.gov.uk service.')) captcha = ReCaptchaField( label='', label_suffix='', ) @property def serialized_data(self): formatted_opportunities = [ '• {opportunity[1]}: {opportunity[0]}'.format(opportunity=item) for item in self.base_fields['opportunities'].choices if item[0] in self.cleaned_data['opportunities'] ] return { **self.cleaned_data, 'opportunity_urls': '\n'.join(formatted_opportunities), } def send_agent_email(self, form_url): sender = Sender(email_address=self.cleaned_data['email_address'], country_code=self.cleaned_data['country']) action = self.action_class( template_id=settings.HPO_GOV_NOTIFY_AGENT_TEMPLATE_ID, email_address=settings.HPO_GOV_NOTIFY_AGENT_EMAIL_ADDRESS, form_url=form_url, sender=sender, ) response = action.save(self.serialized_data) response.raise_for_status() def send_user_email(self, form_url): # no need to set `sender` as this is just a confirmation email. action = self.action_class( template_id=settings.HPO_GOV_NOTIFY_USER_TEMPLATE_ID, email_address=self.cleaned_data['email_address'], form_url=form_url, email_reply_to_id=settings.HPO_GOV_NOTIFY_USER_REPLY_TO_ID, ) response = action.save(self.serialized_data) response.raise_for_status() def save(self, form_url): self.send_agent_email(form_url=form_url) self.send_user_email(form_url=form_url)
class BillModelCreateForm(ModelForm): entity_unit = ChoiceField( required=False, initial=None, widget=Select( attrs={'class': DJANGO_LEDGER_FORM_INPUT_CLASSES + ' is-large'})) def __init__(self, *args, entity_slug, user_model, **kwargs): super().__init__(*args, **kwargs) self.ENTITY_SLUG = entity_slug self.USER_MODEL = user_model self.fields['entity_unit'].choices = [('', '')] + [ (u.slug, u.name) for u in EntityUnitModel.objects.for_entity( entity_slug=self.ENTITY_SLUG, user_model=self.USER_MODEL) ] account_qs = AccountModel.on_coa.for_entity_available( user_model=self.USER_MODEL, entity_slug=self.ENTITY_SLUG) # forcing evaluation of qs to cache results for fields... (avoids 4 database queries, vs 1) len(account_qs) self.fields['cash_account'].queryset = account_qs.filter( role__exact=ASSET_CA_CASH) self.fields['receivable_account'].queryset = account_qs.filter( role__exact=ASSET_CA_RECEIVABLES) self.fields['payable_account'].queryset = account_qs.filter( role__exact=LIABILITY_CL_ACC_PAYABLE) self.fields['earnings_account'].queryset = account_qs.filter( role__in=GROUP_EXPENSES) vendor_qs = VendorModel.objects.for_entity( user_model=self.USER_MODEL, entity_slug=self.ENTITY_SLUG) self.fields['vendor'].queryset = vendor_qs class Meta: model = BillModel fields = [ 'vendor', 'xref', 'date', 'amount_due', 'terms', 'cash_account', 'receivable_account', 'payable_account', 'earnings_account', ] widgets = { 'date': DateInput( attrs={ 'class': DJANGO_LEDGER_FORM_INPUT_CLASSES, 'placeholder': _('Bill Date (YYYY-MM-DD)...') }), 'amount_due': TextInput(attrs={ 'class': DJANGO_LEDGER_FORM_INPUT_CLASSES, 'placeholder': '$$$' }), 'xref': TextInput( attrs={ 'class': DJANGO_LEDGER_FORM_INPUT_CLASSES + ' is-large', 'placeholder': 'External Reference Number...' }), 'terms': Select(attrs={ 'class': DJANGO_LEDGER_FORM_INPUT_CLASSES + ' is-small' }), 'vendor': Select(attrs={'class': DJANGO_LEDGER_FORM_INPUT_CLASSES}), 'cash_account': Select(attrs={'class': DJANGO_LEDGER_FORM_INPUT_CLASSES}), 'receivable_account': Select(attrs={'class': DJANGO_LEDGER_FORM_INPUT_CLASSES}), 'payable_account': Select(attrs={'class': DJANGO_LEDGER_FORM_INPUT_CLASSES}), 'earnings_account': Select(attrs={'class': DJANGO_LEDGER_FORM_INPUT_CLASSES}), }
class Meta: model = Auto fields = '__all__' widgets = { 'name': TextInput(attrs={ 'required': True, 'class': 'form-control' }), 'manufacturer': Select(attrs={ 'required': True, 'class': 'form-control' }), 'body': Select(attrs={ 'required': True, 'class': 'form-control' }), 'fuelType': Select(attrs={ 'required': True, 'class': 'form-control' }), 'fuelRate': NumberInput(attrs={ 'required': True, 'class': 'form-control' }), 'engineVolume': NumberInput(attrs={ 'required': True, 'class': 'form-control' }), 'enginePower': NumberInput(attrs={ 'required': True, 'class': 'form-control' }), 'gearbox': Select(attrs={ 'required': True, 'class': 'form-control' }), 'year': DateInput(attrs={ 'required': True, 'class': 'form-control' }), } labels = { 'name': 'Бренд', 'manufacturer': 'Производитель', 'body': 'Кузов', 'fuelType': 'Топливо', 'fuelRate': 'Расход топлива', 'engineVolume': 'Объем двигателя', 'enginePower': 'Мощность двигателя', 'gearbox': 'Коробка передач', 'year': 'Год выпуска' } error_messages = { 'year': { 'invalid': 'Введите дату в формате ГГГГ-ММ-ДД' } }
class Meta: model = Tipologia fields = [ 'atividade', 'producaoSetor', 'especieDocumental', 'historico', 'finalidade', 'nome', 'identificacao', 'elemento', 'suporte', 'formaDocumental', 'quantidadeVias', 'genero', 'anexo', 'relacaoInterna', 'relacaoExterna', 'inicioAcumulo', 'fimAcumulo', 'quantidadeAcumulada', 'tipoAcumulo', 'embasamentoLegal', 'informacaoOutrosDocumentos', 'restricaoAcesso' ] labels = { 'producaoSetor': 'Este documento é:', 'especieDocumental': 'Espécie documental:', 'identificacao': 'Identificações no documento:', 'formaDocumental': 'Forma documental:', 'elemento': 'Marque os itens presentes neste documento:', 'suporte': 'Em qual suporte a informação circula?', 'anexo': 'Este documento pussui anexo?', 'genero': 'Qual o gênero predominante do documento?', 'nome': 'Nome do documento:', 'finalidade': 'Ação que gerou este documento / Objetivo para o qual foi produzido:', 'relacaoInterna': 'Este documento será encaminhado para outros setores?', 'relacaoExterna': 'Este documento será encaminhado para algum órgão externo ao Ifes?', 'inicioAcumulo': 'Qual o período de abrangência deste tipo de documento?', 'quantidadeAcumulada': 'Qual a quantidade e a forma de armazenamento deste documento?', 'quantidadeVias': 'Produz mais de uma via deste documento?', 'embasamentoLegal': 'Embasamento Legal:', 'informacaoOutrosDocumentos': 'Informações registradas em outros documentos:', 'restricaoAcesso': 'O documento contém informações que necessitam de restrição de acesso?', 'historico': 'Nome do setor presente no documento (se for diferente do nome atual do setor):', } help_texts = { 'nome': 'Dica: Nome utilizado pelo setor para identificar o documento (Ex.: Folha de Ponto; Relatório de Atividades).', 'identificacao': 'Dica: Números e siglas presentes no documento (Ex.: Mem. nº 006-2016-DACV)', 'embasamentoLegal': 'Dica: Existe alguma normativa ou legislação específica sobre a configuração (Boletim, certidão, etc) que este documento possui e o conteúdo tratado nele?', 'informacaoOutrosDocumentos': 'Dica: As informações que estão neste documento encontram-se também em outros? (Ex: relatórios parciais que têm suas informações compiladas em um relatório final)', } widgets = { 'quantidadeAcumulada': Select(attrs={'onchange': 'quantidadeObrigatoriaAcumulada(this)'}), 'tipoAcumulo': Select(attrs={'onchange': 'quantidadeObrigatoriaTipo(this)'}), }
class UserRegistrationCourseFormBase(ModelForm): pesel = PLPESELField(max_length=11, label=_("PESEL"), widget=TextInput(attrs={'type': 'number'}), required=False) postal_code = RegexField(label=_("Postal code"), regex=r"(?i)^[a-z0-9][a-z0-9\- ]{0,10}[a-z0-9]$") email = EmailField(label=_("E-mail address")) phone = CharField(label=_("Phone"), max_length=30) status_info = CharField(required=False, label=_("Status additional information"), widget=Select()) statement1 = BooleanField(required=True) statement2 = BooleanField(required=True) def __init__(self, *args, **kwargs): super(UserRegistrationCourseFormBase, self).__init__(*args, **kwargs) self.fields['statement1'].label = _( "I agree with <a href='{url}' target='_blank'>the project participant's declaration.</a>" ).format(url=static(settings.STATEMENT1_PDF)) self.fields['statement2'].label = _( "I consent to <a href='{url}' target='_blank'>the processing of my personal data to participate in the project.</a>" ).format(url=static(settings.STATEMENT2_PDF)) self.helper = FormHelper(self) self.helper.layout = Layout( Fieldset( '', Div(HTML( '<div class="col-lg-4 pl-lg-0 px-0"><h3 class="h4 mx-0">{}</h3></div>' .format(_("Participant details"))), Div(Div(Div( 'first_name', css_class="col-md-6 register-course__input-container"), Div('last_name', css_class= "col-md-6 register-course__input-container"), css_class="row"), Div(Div('citizenship', css_class= "col-md-6 register-course__input-container"), Div('pesel', css_class= "col-md-6 register-course__input-container"), css_class="row"), Div(Div('gender', css_class= "col-md-3 register-course__input-container"), Div('age', css_class= "col-md-3 register-course__input-container"), Div('education', css_class= "col-md-6 register-course__input-container"), css_class="row"), css_class="group col-lg-8 ml-lg-auto px-0"), css_class="d-flex flex-wrap"), Div(HTML('<hr class="w-100 pb-40" />'), HTML( '<div class="col-lg-4 pl-lg-0 px-0"><h3 class="h4 mx-0 w-67">{}</h3></div>' .format(_("Contact details / Postal address"))), Div(Div(Div( 'phone', css_class="col-md-6 register-course__input-container"), Div('email', css_class= "col-md-6 register-course__input-container"), css_class="row"), Div(Div('street', css_class= "col-md-6 register-course__input-container"), Div('street_no', css_class= "col-md-3 register-course__input-container"), Div('street_building_no', css_class= "col-md-3 register-course__input-container"), Div('postal_code', css_class= "col-md-6 register-course__input-container"), Div('city', css_class= "col-md-6 register-course__input-container"), css_class="row"), Div(Div('country', css_class= "col-md-6 register-course__input-container"), Div('voivodeship', css_class= "col-md-6 register-course__input-container"), Div('county', css_class= "col-md-6 register-course__input-container"), Div('commune', css_class= "col-md-6 register-course__input-container"), css_class="row"), css_class="group col-lg-8 ml-lg-auto px-0"), css_class="d-flex flex-wrap"), Div(HTML('<hr class="w-100 pb-40" />'), HTML( '<div class="col-lg-4 pl-lg-0 px-0"><h3 class="h4 mx-0">{}</h3></div>' .format(_("Additional information"))), Div(Div(Div( 'status', css_class="col-md-12 register-course__input-container" ), Div('status_info', css_class= "col-md-12 register-course__input-container"), Div('profession', css_class= "col-md-6 register-course__input-container"), Div('work_name', css_class= "col-md-6 register-course__input-container"), css_class="row"), Div(Div('start_project_date', css_class= "col-md-12 register-course__input-container"), Div('end_project_date', css_class= "col-md-12 register-course__input-container"), Div('start_support_date', css_class= "col-md-12 register-course__input-container"), css_class="row d-none"), Div(Div('origin', css_class= "col-md-12 register-course__input-container"), Div('homeless', css_class= "col-md-12 register-course__input-container"), Div('disabled_person', css_class= "col-md-12 register-course__input-container"), Div('social_disadvantage', css_class= "col-md-12 register-course__input-container"), css_class="row align-items-end"), css_class="group col-lg-8 ml-lg-auto px-0"), css_class="d-flex flex-wrap"), ), Div(HTML('<hr class="w-100 pb-40" />'), HTML( '<div class="col-lg-4 pl-lg-0 px-0"><h3 class="h4 mx-0">{}</h3></div>' .format(_("Required consents"))), Div('statement1', 'statement2', css_class="group mb-md-5 mb-4 col-lg-8 ml-lg-auto px-0"), css_class="d-flex flex-wrap"), Div( HTML('<hr class="w-100 pb-30 my-0" />'), Div(HTML( '<div class="col-lg-2 col-xs-12 col-md-3 mr-lg-auto order-3 order-md-1 d-flex"><img src="/static/images/logo-navoica.svg" alt="Logo Navoica.pl" class="navoica-logo img-fluid align-self-center" /></div>' ), Div(HTML( '<button class="btn btn-cancel rounded-0 mr-lg-5 mr-md-2 d-none">{}</button>' .format(_("Cancel"))), ButtonHolder( Submit('submit', _("Register me for the course"), css_class= 'button white w-100 rounded-0 btn-submit')), css_class= 'form-buttons d-flex flex-wrap oder-1 order-md-2 justify-content-between flex-column flex-md-row' ), css_class= 'd-flex justify-content-between flex-wrap align-items-center' )), ) class Meta: model = UserRegistrationCourse exclude = ('user', 'course_id', 'language_code') widgets = { 'origin': RadioSelect(attrs={'required': 'required'}), 'homeless': RadioSelect(attrs={'required': 'required'}), 'disabled_person': RadioSelect(attrs={'required': 'required'}), 'social_disadvantage': RadioSelect(attrs={'required': 'required'}) }
class Meta: model = House fields = [ 'title', 'slug', 'description', 'keywords', 'category', 'image', 'price', 'aidat', 'buildTime', 'kat', 'katsayisi', 'area', 'cephe', 'bedroom', 'bathroom', 'KrediUygun', 'isinmatip', 'esyaDurum', 'yapiTipi', 'kullanimDurumu', 'tapuDurumu', 'takas', 'garage', 'city', 'locationDetail', 'district', 'detail' ] widgets = { 'title': TextInput(attrs={ 'placeholder': 'title', 'class': 'form-control' }), 'slug': TextInput(attrs={ 'placeholder': 'slug', 'class': 'form-control' }, ), 'description': TextInput(attrs={ 'placeholder': 'description', 'class': 'form-control' }), 'keywords': TextInput(attrs={ 'placeholder': 'keywords', 'class': 'form-control' }), 'category': Select(attrs={ 'placeholder': 'category', 'class': 'form-control' }), 'price': NumberInput(attrs={ 'placeholder': 'price', 'class': 'form-control', 'onclick': 'commas(self)' }, ), 'buildTime': NumberInput(attrs={ 'placeholder': 'buildTime', 'class': 'form-control' }), 'kat': NumberInput(attrs={ 'placeholder': 'kat', 'class': 'form-control' }), 'aidat': NumberInput(attrs={ 'placeholder': 'aidat', 'class': 'form-control' }), 'isinmatip': TextInput(attrs={ 'placeholder': 'isinmatip', 'class': 'form-control' }), 'katsayisi': NumberInput(attrs={ 'placeholder': 'katsayisi', 'class': 'form-control' }), 'KrediUygun': Select(attrs={ 'placeholder': 'KrediUygun', 'class': 'form-control' }), 'esyaDurum': Select(attrs={ 'placeholder': 'esyaDurum', 'class': 'form-control' }), 'yapiTipi': Select(attrs={ 'placeholder': 'yapiTipi', 'class': 'form-control' }), 'kullanimDurumu': Select(attrs={ 'placeholder': 'kullanimDurumu', 'class': 'form-control' }), 'tapuDurumu': Select(attrs={ 'placeholder': 'tapuDurumu', 'class': 'form-control' }), 'takas': Select(attrs={ 'placeholder': 'kat', 'takas': 'form-control' }), 'cephe': Select(attrs={ 'placeholder': 'kat', 'cephe': 'form-control' }), 'area': NumberInput(attrs={ 'placeholder': 'area', 'class': 'form-control' }), 'bedroom': NumberInput(attrs={ 'placeholder': 'bedroom', 'class': 'form-control' }), 'bathroom': NumberInput(attrs={ 'placeholder': 'bathroom', 'class': 'form-control' }), 'garage': NumberInput(attrs={ 'placeholder': 'garage', 'class': 'form-control' }), 'city': Select(attrs={ 'placeholder': 'city', 'class': 'form-control' }), 'district': TextInput(attrs={ 'placeholder': 'district', 'class': 'form-control' }), 'locationDetail': TextInput(attrs={ 'placeholder': 'locationDetail', 'class': 'form-control' }), 'image': FileInput(attrs={ 'placeholder': 'image', 'class': 'form-control' }), 'detail': CKEditorWidget(), }
class RecordForm(LRecordForm): experiment = ModelChoiceField(queryset=Experiment.objects.exclude( experiment='TEM preparation').exclude(experiment='FIB'), help_text='Pick an experiment', label='Experiment:', widget=Select(attrs={ 'class': 'experiment', })) class Meta(LRecordForm.Meta): model = Record fields = [ 'date_from', 'user', 'wu', 'group', 'project', 'experiment', 'remark' ] labels = { 'wu': 'N samples:', 'date_from': 'Date:', 'time_from': 'Time:', 'date_to': 'To:', 'time_to': 'Time:', 'experiment': 'Experiment:', 'nights': 'N nights:', } help_texts = { 'date_from': 'The starting date of your run', 'date_to': 'The last date of your run', 'time_from': 'The first session of your run', 'time_to': 'The last session of your run', 'nights': 'If your run went late (after 20h), add the number of late nights you did', 'experiment': 'Pick an experiment', 'wu': 'Enter the number of samples you prepared', } widgets = { 'date_from': DateInput(attrs={ 'type': 'date', 'class': 'datepicker dfrom time' }), 'date_to': DateInput(attrs={ 'type': 'date', 'class': 'datepicker dto time' }), 'time_to': Select(attrs={'class': 'tto time'}), 'time_from': Select(attrs={'class': 'tfrom time'}), 'remark': Textarea( attrs={ 'placeholder': 'Enter some detail here about your experiment', 'rows': '1', 'cols': '50' }), 'experiment': Select(attrs={ 'class': 'experiment', }), 'group': Select(attrs={ 'class': 'group', }), 'project': Select(attrs={ 'class': 'project', }), 'user': Select(attrs={ 'placeholder': 'Surname Name', 'class': 'user' }), 'wu': NumberInput( attrs={ 'required': False, 'class': 'uo', 'value': 0, 'min': 0, 'step': 0.5, 'style': 'width:10ch', }), 'nights': NumberInput(attrs={ 'class': 'nights time', 'value': 0, 'min': 0, 'step': 1 }), } def __init__(self, *args, **kwargs): self.helper = FormHelper() self.help_text_inline = False self.helper.form_class = 'form-horizontal formclass' self.helper.form_id = 'form_id' self.helper.form_tag = True self.helper.layout = Layout( Div( Row(Column('date_from', css_class='form-group col-3'), Column('experiment', css_class='form-group col-5'), Column('wu', css_class='form-group col-4 uocol'), css_class='form-row'), Row(Column('project', css_class='form-group col-md-12'), ), Row(Column('user', css_class='form-group col-md-5 mr-2'), Column('user_text_name', css_class='form-group col-md-3 usercol'), Column('user_text_surname', css_class='form-group col-md-3 usercol'), Column('group', css_class='form-group col-md-4'), css_class='form-row'), Row( Column('remark', css_class='form-group mr-5'), Column( FormActions( Button( 'okbutton', 'Submit', css_class='btn-primary okclass' ), #form will be triggered using a popup jquery, see static/js/osp_records.js Reset('name', 'Reset', css_class='btn-secondary')), css_class='form-group align-items-center')), )) super().__init__(*args, **kwargs) for field in self.fields: help_text = self.fields[field].help_text self.fields[field].help_text = None if help_text != '': if 'class' in self.fields[field].widget.attrs: self.fields[field].widget.attrs['class'] += ' has-popover' self.fields[field].widget.attrs.update({ 'data - toggle': 'popover', 'data-content': help_text, 'data-placement': 'right', 'data-container': 'body' })
class Meta(LRecordForm.Meta): model = Record fields = [ 'date_from', 'time_from', 'date_to', 'time_to', 'user', 'wu', 'nights', 'group', 'project', 'experiment', 'remark' ] labels = { 'wu': 'WU:', 'date_from': 'From:', 'time_from': 'Time:', 'date_to': 'To:', 'time_to': 'Time:', 'experiment': 'Experiment:', 'nights': 'N nights:', } help_texts = { 'date_from': 'The starting date of your run', 'date_to': 'The last date of your run', 'time_from': 'The first session of your run', 'time_to': 'The last session of your run', 'nights': 'If your run went late (after 20h), add the number of late nights you did', 'experiment': 'Pick an experiment' } widgets = { 'date_from': DateInput(attrs={ 'type': 'date', 'class': 'datepicker dfrom time' }), 'date_to': DateInput(attrs={ 'type': 'date', 'class': 'datepicker dto time' }), 'time_to': Select(attrs={'class': 'tto time'}), 'time_from': Select(attrs={'class': 'tfrom time'}), 'remark': Textarea( attrs={ 'placeholder': 'Enter some detail here about your experiment', 'rows': '1', 'cols': '50' }), 'experiment': Select(attrs={ 'class': 'experiment', }), 'group': Select(attrs={ 'class': 'group', }), 'project': Select(attrs={ 'class': 'project', }), 'user': Select(attrs={ 'placeholder': 'Surname Name', 'class': 'user' }), 'wu': NumberInput( attrs={ 'required': False, 'class': 'uo', 'value': 0, 'min': 0, 'step': 0.5, 'style': 'width:10ch' }), 'nights': NumberInput(attrs={ 'class': 'nights time', 'value': 0, 'min': 0, 'step': 1 }), }
class Meta: model = MatchPrediction exclude = ['created', 'predicted_radiant_win'] widgets = { 'model': Select(attrs={'class': 'form-control'}), }
class CopyForm(Form): degree = IntegerField(widget=Select( choices=((1, gettext_lazy('test')), )))
class RecordForm(LRecordForm): subexps = OrderedDict([('STM/AFM', ['LT-U', 'DUF']), ('Prepa', ['LT-U', 'LT-4', 'DUF']), ('Maintenance', ['LT-U', 'DUF', 'LT-4']), ('Topo', ['LT-4']), ('Spectro', ['DUF']), ('Atom-Manipulation', ['LT-4']), ('Tunneling_measurement', ['LT-4'])]) subexp = ChoiceFieldnovalidate(choices=[ (ind, k) for ind, k in enumerate(subexps.keys()) ], label='Usage:', widget=Select(attrs={ 'class': 'subexpclass', })) class Meta(LRecordForm.Meta): model = Record fields = [ 'date_from', 'time_from', 'date_to', 'time_to', 'user', 'wu', 'group', 'project', 'experiment', 'remark' ] labels = { 'wu': 'WU:', 'date_from': 'From:', 'time_from': 'Time:', 'date_to': 'To:', 'time_to': 'Time:', 'experiment': 'Experiment:', } help_texts = { 'date_from': 'The starting date of your run', 'date_to': 'The last date of your run', 'time_from': 'The first session of your run', 'time_to': 'The last session of your run', 'experiment': 'Pick an experiment' } widgets = { 'date_from': DateInput(attrs={ 'type': 'date', 'class': 'datepicker dfrom time' }), 'date_to': DateInput(attrs={ 'type': 'date', 'class': 'datepicker dto time' }), 'time_to': Select(attrs={'class': 'tto time'}), 'time_from': Select(attrs={'class': 'tfrom time'}), 'remark': Textarea( attrs={ 'placeholder': 'Enter some detail here about your experiment', 'rows': '1', 'cols': '50' }), 'experiment': Select(attrs={ 'class': 'experiment', }), 'group': Select(attrs={ 'class': 'group', }), 'project': Select(attrs={ 'class': 'project', }), 'user': Select(attrs={ 'placeholder': 'Surname Name', 'class': 'user' }), 'wu': NumberInput( attrs={ 'required': False, 'class': 'uo', 'value': 0, 'min': 0, 'step': 0.5, 'style': 'width:10ch' }), } def __init__(self, *args, **kwargs): self.helper = FormHelper() self.help_text_inline = False self.helper.form_class = 'form-horizontal formclass' self.helper.form_id = 'form_id' self.helper.form_tag = True self.helper.layout = Layout( Div( Row(Column('date_from', css_class='form-group col-md-3'), Column('time_from', css_class='form-group col-md-3'), Column('experiment', css_class='form-group col-6'), Div(css_class='w-100'), Column('date_to', css_class='form-group col-md-3'), Column('time_to', css_class='form-group col-md-3'), Column('wu', css_class='form-group col-md-4 uocol'), css_class='form-row'), Row( Column('project', css_class='form-group col-md-8'), Column('subexp', css_class='form-group col-md-4'), css_class='form-row', ), Row(Column('user', css_class='form-group col-md-5'), Column('user_text_name', css_class='form-group col-md-3 usercol'), Column('user_text_surname', css_class='form-group col-md-3 usercol'), Column('group', css_class='form-group col-md-2'), css_class='form-row'), Row( Column('remark', css_class='form-group mr-5'), Column( FormActions( Button( 'okbutton', 'Submit', css_class='btn-primary okclass' ), #form will be triggered using a popup jquery, see static/js/osp_records.js Reset('name', 'Reset', css_class='btn-secondary')), css_class='form-group align-items-center')), )) super().__init__(*args, **kwargs) for field in self.fields: help_text = self.fields[field].help_text self.fields[field].help_text = None if help_text != '': if 'class' in self.fields[field].widget.attrs: self.fields[field].widget.attrs['class'] += ' has-popover' self.fields[field].widget.attrs.update({ 'data - toggle': 'popover', 'data-content': help_text, 'data-placement': 'right', 'data-container': 'body' }) def clean_subexp(self): data = self.cleaned_data['subexp'] if data == '': return None return list(self.subexps.keys())[int(data)]
'post__id', 'post__title', 'post__url', 'post__slug', 'post__blog__user__id', 'post__blog__user__hacker__avatar_url', 'post__blog__stream', ) # Count the visits entries = entries.annotate(total=Count('post__id')) # Get top 'n' posts entries = entries.order_by('total').reverse()[:n] return entries def _get_tsv(entry): return '{post__id}\t{post__title}\t{post__url}\t{total}'.format(**entry) BlogForm = modelform_factory( Blog, fields=("feed_url", "stream"), widgets={ 'feed_url': TextInput(attrs={ 'class': 'form-control', 'type': 'url' }), 'stream': Select(attrs={'class': 'custom-select'}), }, )
def __init__(self, attrs=None): widgets = ( Select(attrs=attrs, choices=EXP_MONTH), Select(attrs=attrs, choices=EXP_YEAR) ) super(ExpWidget, self).__init__(widgets, attrs)
class SelectTest(WidgetTest): widget = Select nested_widget = Select(choices=( ('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))), )) def test_render(self): self.check_html(self.widget(choices=self.beatles), 'beatle', 'J', html=("""<select name="beatle"> <option value="J" selected>John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""")) def test_render_none(self): """ If the value is None, none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatle', None, html=("""<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""")) def test_render_label_value(self): """ If the value corresponds to a label (but not to an option value), none of the options are selected. """ self.check_html(self.widget(choices=self.beatles), 'beatle', 'John', html=("""<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""")) def test_render_selected(self): """ Only one option can be selected (#8103). """ choices = [('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra')] self.check_html(self.widget(choices=choices), 'choices', '0', html=("""<select name="choices"> <option value="0" selected>0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="0">extra</option> </select>""")) def test_constructor_attrs(self): """ Select options shouldn't inherit the parent widget attrs. """ widget = Select( attrs={ 'class': 'super', 'id': 'super' }, choices=[(1, 1), (2, 2), (3, 3)], ) self.check_html(widget, 'num', 2, html=("""<select name="num" class="super" id="super"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""")) def test_compare_to_str(self): """ The value is compared to its str(). """ self.check_html( self.widget(choices=[('1', '1'), ('2', '2'), ('3', '3')]), 'num', 2, html=("""<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>"""), ) self.check_html( self.widget(choices=[(1, 1), (2, 2), (3, 3)]), 'num', '2', html=("""<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>"""), ) self.check_html( self.widget(choices=[(1, 1), (2, 2), (3, 3)]), 'num', 2, html=("""<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>"""), ) def test_choices_constructor(self): widget = Select(choices=[(1, 1), (2, 2), (3, 3)]) self.check_html(widget, 'num', 2, html=("""<select name="num"> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select>""")) def test_choices_constructor_generator(self): """ If choices is passed to the constructor and is a generator, it can be iterated over multiple times without getting consumed. """ def get_choices(): for i in range(5): yield (i, i) widget = Select(choices=get_choices()) self.check_html(widget, 'num', 2, html=("""<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> <option value="4">4</option> </select>""")) self.check_html(widget, 'num', 3, html=("""<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3" selected>3</option> <option value="4">4</option> </select>""")) def test_choices_escaping(self): choices = (('bad', 'you & me'), ('good', mark_safe('you > me'))) self.check_html(self.widget(choices=choices), 'escape', None, html=("""<select name="escape"> <option value="bad">you & me</option> <option value="good">you > me</option> </select>""")) def test_choices_unicode(self): self.check_html( self.widget(choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), 'email', 'ŠĐĆŽćžšđ', html=("""<select name="email"> <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111 </option> <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option> </select>"""), ) def test_choices_optgroup(self): """ Choices can be nested one level in order to create HTML optgroups. """ self.check_html(self.nested_widget, 'nestchoice', None, html=("""<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group "1""> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""")) def test_choices_select_outer(self): self.check_html(self.nested_widget, 'nestchoice', 'outer1', html=("""<select name="nestchoice"> <option value="outer1" selected>Outer 1</option> <optgroup label="Group "1""> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""")) def test_choices_select_inner(self): self.check_html(self.nested_widget, 'nestchoice', 'inner1', html=("""<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group "1""> <option value="inner1" selected>Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""")) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_doesnt_localize_option_value(self): choices = [ (1, 'One'), (1000, 'One thousand'), (1000000, 'One million'), ] html = """ <select name="number"> <option value="1">One</option> <option value="1000">One thousand</option> <option value="1000000">One million</option> </select> """ self.check_html(self.widget(choices=choices), 'number', None, html=html) choices = [ (datetime.time(0, 0), 'midnight'), (datetime.time(12, 0), 'noon'), ] html = """ <select name="time"> <option value="00:00:00">midnight</option> <option value="12:00:00">noon</option> </select> """ self.check_html(self.widget(choices=choices), 'time', None, html=html) def test_options(self): options = list( self.widget(choices=self.beatles).options( 'name', ['J'], attrs={'class': 'super'}, )) self.assertEqual(len(options), 4) self.assertEqual(options[0]['name'], 'name') self.assertEqual(options[0]['value'], 'J') self.assertEqual(options[0]['label'], 'John') self.assertEqual(options[0]['index'], '0') self.assertEqual(options[0]['selected'], True) # Template-related attributes self.assertEqual(options[1]['name'], 'name') self.assertEqual(options[1]['value'], 'P') self.assertEqual(options[1]['label'], 'Paul') self.assertEqual(options[1]['index'], '1') self.assertEqual(options[1]['selected'], False) def test_optgroups(self): choices = [ ('Audio', [ ('vinyl', 'Vinyl'), ('cd', 'CD'), ]), ('Video', [ ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ]), ('unknown', 'Unknown'), ] groups = list( self.widget(choices=choices).optgroups( 'name', ['vhs'], attrs={'class': 'super'}, )) audio, video, unknown = groups label, options, index = audio self.assertEqual(label, 'Audio') self.assertEqual(options, [{ 'value': 'vinyl', 'type': 'select', 'attrs': {}, 'index': '0_0', 'label': 'Vinyl', 'template_name': 'django/forms/widgets/select_option.html', 'name': 'name', 'selected': False, 'wrap_label': True, }, { 'value': 'cd', 'type': 'select', 'attrs': {}, 'index': '0_1', 'label': 'CD', 'template_name': 'django/forms/widgets/select_option.html', 'name': 'name', 'selected': False, 'wrap_label': True, }]) self.assertEqual(index, 0) label, options, index = video self.assertEqual(label, 'Video') self.assertEqual(options, [{ 'value': 'vhs', 'template_name': 'django/forms/widgets/select_option.html', 'label': 'VHS Tape', 'attrs': { 'selected': True }, 'index': '1_0', 'name': 'name', 'selected': True, 'type': 'select', 'wrap_label': True, }, { 'value': 'dvd', 'template_name': 'django/forms/widgets/select_option.html', 'label': 'DVD', 'attrs': {}, 'index': '1_1', 'name': 'name', 'selected': False, 'type': 'select', 'wrap_label': True, }]) self.assertEqual(index, 1) label, options, index = unknown self.assertEqual(label, None) self.assertEqual(options, [{ 'value': 'unknown', 'selected': False, 'template_name': 'django/forms/widgets/select_option.html', 'label': 'Unknown', 'attrs': {}, 'index': '2', 'name': 'name', 'type': 'select', 'wrap_label': True, }]) self.assertEqual(index, 2) def test_optgroups_integer_choices(self): """The option 'value' is the same type as what's in `choices`.""" groups = list( self.widget(choices=[[0, 'choice text']]).optgroups( 'name', ['vhs'])) label, options, index = groups[0] self.assertEqual(options[0]['value'], 0) def test_deepcopy(self): """ __deepcopy__() should copy all attributes properly (#25085). """ widget = Select() obj = copy.deepcopy(widget) self.assertIsNot(widget, obj) self.assertEqual(widget.choices, obj.choices) self.assertIsNot(widget.choices, obj.choices) self.assertEqual(widget.attrs, obj.attrs) self.assertIsNot(widget.attrs, obj.attrs) def test_doesnt_render_required_when_impossible_to_select_empty_field( self): widget = self.widget(choices=[('J', 'John'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), False) def test_renders_required_when_possible_to_select_empty_field_str(self): widget = self.widget(choices=[('', 'select please'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_renders_required_when_possible_to_select_empty_field_list(self): widget = self.widget(choices=[['', 'select please'], ['P', 'Paul']]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_renders_required_when_possible_to_select_empty_field_none(self): widget = self.widget(choices=[(None, 'select please'), ('P', 'Paul')]) self.assertIs(widget.use_required_attribute(initial=None), True) def test_doesnt_render_required_when_no_choices_are_available(self): widget = self.widget(choices=[]) self.assertIs(widget.use_required_attribute(initial=None), False)
class UKEFContactForm(GovNotifyEmailActionMixin, forms.Form): full_name = forms.CharField( label=_('Full name'), min_length=2, max_length=50, error_messages={ 'required': _('Enter your full name'), }, ) job_title = forms.CharField( label=_('Job title'), max_length=50, error_messages={ 'required': _('Enter your job title'), }, ) email = forms.EmailField( label=_('Business email address'), error_messages={ 'required': _('Enter an email address in the correct format, like [email protected]' ), 'invalid': _('Enter an email address in the correct format, like [email protected]' ), }, ) business_name = forms.CharField( label=_('Business name'), max_length=50, error_messages={ 'required': _('Enter your business name'), }, ) business_website = forms.CharField( label=_('Business website'), max_length=255, error_messages={ 'required': _('Enter a website address in the correct format, like https://www.example.com or www.company.com' ), 'invalid': _('Enter a website address in the correct format, like https://www.example.com or www.company.com' ), }, required=False, ) country = forms.ChoiceField( label=_('Which country are you based in?'), widget=Select(), choices=COUNTRIES, ) like_to_discuss = forms.ChoiceField( label=_( 'Do you have a specific project or proposal you’d like to discuss?' ), choices=( ('no', 'No'), ('yes', 'Yes'), ), widget=forms.RadioSelect, error_messages={'required': _('Please answer this question')}, ) like_to_discuss_other = forms.ChoiceField( label=_('Which country is the project located in?'), widget=Select(), choices=COUNTRIES, required=False, ) how_can_we_help = forms.CharField( label=_('How can we help?'), help_text=_( 'Please tell us briefly what type of support you’re looking for'), widget=Textarea, ) terms_agreed = forms.BooleanField( label=TERMS_LABEL, error_messages={ 'required': _('You must agree to the terms and conditions' ' before registering'), }, ) captcha = ReCaptchaField( label='', label_suffix='', widget=ReCaptchaV3(), ) @property def serialized_data(self): data = super().serialized_data countries_mapping = dict(COUNTRY_CHOICES) country_label = countries_mapping.get(data['country']) data['country_label'] = country_label data['like_to_discuss_country'] = '' if data.get('like_to_discuss') == 'yes': data['like_to_discuss_country'] = countries_mapping.get( data['like_to_discuss_other']) return data
class Meta: model = ErrorTemplate fields = ('name', 'error_400_mode', 'error_400_url', 'error_400_html', 'error_403_mode', 'error_403_url', 'error_403_html', 'error_405_mode', 'error_405_url', 'error_405_html', 'error_408_mode', 'error_408_url', 'error_408_html', 'error_425_mode', 'error_425_url', 'error_425_html', 'error_429_mode', 'error_429_url', 'error_429_html', 'error_500_mode', 'error_500_url', 'error_500_html', 'error_502_mode', 'error_502_url', 'error_502_html', 'error_503_mode', 'error_503_url', 'error_503_html', 'error_504_mode', 'error_504_url', 'error_504_html') widgets = { 'name': TextInput(attrs={'class': 'form-control'}), 'error_400_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_400_url': TextInput(attrs={'class': 'form-control'}), 'error_400_html': Textarea(attrs={'class': 'form-control'}), 'error_403_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_403_url': TextInput(attrs={'class': 'form-control'}), 'error_403_html': Textarea(attrs={'class': 'form-control'}), 'error_405_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_405_url': TextInput(attrs={'class': 'form-control'}), 'error_405_html': Textarea(attrs={'class': 'form-control'}), 'error_408_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_408_url': TextInput(attrs={'class': 'form-control'}), 'error_408_html': Textarea(attrs={'class': 'form-control'}), 'error_425_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_425_url': TextInput(attrs={'class': 'form-control'}), 'error_425_html': Textarea(attrs={'class': 'form-control'}), 'error_429_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_429_url': TextInput(attrs={'class': 'form-control'}), 'error_429_html': Textarea(attrs={'class': 'form-control'}), 'error_500_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_500_url': TextInput(attrs={'class': 'form-control'}), 'error_500_html': Textarea(attrs={'class': 'form-control'}), 'error_502_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_502_url': TextInput(attrs={'class': 'form-control'}), 'error_502_html': Textarea(attrs={'class': 'form-control'}), 'error_503_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_503_url': TextInput(attrs={'class': 'form-control'}), 'error_503_html': Textarea(attrs={'class': 'form-control'}), 'error_504_mode': Select(choices=ERROR_MODE_CHOICES, attrs={'class': 'form-control select2 mode'}), 'error_504_url': TextInput(attrs={'class': 'form-control'}), 'error_504_html': Textarea(attrs={'class': 'form-control'}), }
'uploads/' + self.instance.slug + '/' + get_valid_filename(form.cleaned_data.get('media').name)): form.cleaned_data['DELETE'] = True DevelopmentMediaFormSet = inlineformset_factory( Development, DevelopmentMedia, formset=BaseDevelopmentMediaFormSet, fields=('media', 'development_type'), extra=1, validate_max=True, widgets={ 'media': MediaClearableFileInput(attrs={'multiple': True}), 'development_type': Select(attrs={'class': 'form-control select-fix-height'}), }) DevelopmentMediaDirectoryFormSet = inlineformset_factory( Development, DevelopmentMedia, formset=BaseDevelopmentMediaFormSet, fields=('media', 'development_type'), extra=1, validate_max=True, widgets={ 'media': MediaClearableFileInput(attrs={ 'webkitdirectory': True, 'mozdirectory': True }),
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["service"].widget = Select( choices=settings.SCENE_PLAYLIST_ACCEPTED_SERVICES)
def __init__(self, attrs=None): widgets = (Select(attrs=attrs, choices=phone_prefixes), TextInput()) # pylint: disable=bad-super-call super(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)
class BGFinProdSurveyOrgCommonForm(Form): issuer_full_name = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_short_name = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_foreign_name = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_legal_address = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_fact_address = CharField( required=False, widget=TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Обязательно к заполнению' })) issuer_ogrn = CharField(required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_inn = CharField(required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_kpp = CharField(required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_okpo = CharField(required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_registration_date = DateField( required=False, widget=DateInput(attrs={'class': 'form-control'})) issuer_ifns_reg_date = DateField( required=False, widget=DateInput(attrs={'class': 'form-control'})) issuer_ifns_reg_cert_number = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_okopf = CharField(required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_okved = CharField(required=False, widget=TextInput(attrs={'class': 'form-control'})) avg_employees_cnt_for_prev_year = IntegerField( required=False, widget=NumberInput(attrs={'class': 'form-control'})) issuer_web_site = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_accountant_org_or_person = CharField( required=False, widget=TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Обязательно к заполнению' })) issuer_post_address = CharField( required=False, widget=TextInput(attrs={'class': 'form-control'})) issuer_has_overdue_debts_for_last_180_days = BooleanField( required=False, widget=Select(attrs={'class': 'form-control'}, choices=[ (False, 'Нет'), (True, 'Да'), ])) issuer_overdue_debts_info = CharField(required=False, widget=Textarea(attrs={ 'class': 'form-control', 'rows': 3 })) tax_system = CharField(required=True, widget=Select(attrs={'class': 'form-control check'}, choices=[ (None, '---Обязательно к выбору---'), (consts.TAX_USN, 'УСН'), (consts.TAX_OSN, 'ОСН'), (consts.TAX_ENVD, 'ЕНВД'), (consts.TAX_ESHD, 'ЕСХД'), ])) agent_comission = DecimalField( decimal_places=2, required=False, widget=TextInput( attrs={ 'class': 'form-control input-sm', 'placeholder': 'Предложить комиссию(руб)' }))
class Meta: model = ficha_nutricion fields = [ 'lacteos', 'vegetales', 'frutas', 'cho', 'carnes', 'comidas_rapidas', 'frituras', 'enlatados', 'gaseosas', 'energizantes', 'infusiones', 'lacteos_input', 'vegetales_input', 'frutas_input', 'cho_input', 'carnes_input', 'comidas_rapidas_input', 'frituras_input', 'enlatados_input', 'gaseosas_input', 'energizantes_input', 'infusiones_input', 'pregunta1', 'pregunta2', 'pregunta3', 'pregunta4', 'pregunta5', 'pregunta6', 'proteina', 'grasas', 'carbohidratos', 'dieta' ] labels = { 'lacteos': 'Lacteos', 'vegetales': 'Vegetales', 'frutas': 'Frutas', 'cho': 'CHO', 'carnes': 'Carnes', 'comidas_rapidas': 'Comidas Rapidas', 'frituras': 'Frituras', 'enlatados': 'Alimentos Enlatados', 'gaseosas': 'Bebidas Gaseosas', 'energizantes': 'Bebidas Energizantes', 'infusiones': 'Infusiones', 'lacteos_input': 'Veces', 'vegetales_input': 'Veces', 'frutas_input': 'Veces', 'cho_input': 'Veces', 'carnes_input': 'Veces', 'comidas_rapidas_input': 'Veces', 'frituras_input': 'Veces', 'enlatados_input': 'Veces', 'gaseosas_input': 'Veces', 'energizantes_input': 'Veces', 'infusiones_input': 'Veces', 'pregunta1': 'Sufre algun tipo de enfermedad digestiva?', 'pregunta2': 'Cuando esta solo le da por comer mas?', 'pregunta3': 'Cuantas horas de sueno realiza?', 'pregunta4': 'Cuantas comidas realiza en el dia?', 'pregunta5': 'Como son las preparaciones de las comidas?', 'pregunta6': 'Que cantidad de agua consume?', 'proteina': 'Proteinas', 'grasas': 'Grasas', 'carbohidratos': 'Carbohidratos' } widgets = { 'lacteos': Select(attrs={'class': u'form-control'}), 'vegetales': Select(attrs={'class': u'form-control'}), 'frutas': Select(attrs={'class': u'form-control'}), 'cho': Select(attrs={'class': u'form-control'}), 'carnes': Select(attrs={'class': u'form-control'}), 'comidas_rapidas': Select(attrs={'class': u'form-control'}), 'frituras': Select(attrs={'class': u'form-control'}), 'enlatados': Select(attrs={'class': u'form-control'}), 'gaseosas': Select(attrs={'class': u'form-control'}), 'energizantes': Select(attrs={'class': u'form-control'}), 'infusiones': Select(attrs={'class': u'form-control'}), 'lacteos_input': HorizontalRadioSelect(), 'vegetales_input': HorizontalRadioSelect(), 'frutas_input': HorizontalRadioSelect(), 'cho_input': HorizontalRadioSelect(), 'carnes_input': HorizontalRadioSelect(), 'comidas_rapidas_input': HorizontalRadioSelect(), 'frituras_input': HorizontalRadioSelect(), 'enlatados_input': HorizontalRadioSelect(), 'gaseosas_input': HorizontalRadioSelect(), 'energizantes_input': HorizontalRadioSelect(), 'infusiones_input': HorizontalRadioSelect(), 'pregunta1': Textarea( attrs={ 'class': u'form-control', 'placeholder': u'Ingrese respuesta ...', 'rows': 10, 'cols': 40, 'style': 'height: 6em;' }), 'pregunta2': Textarea( attrs={ 'class': u'form-control', 'placeholder': u'Ingrese respuesta ...', 'rows': 10, 'cols': 40, 'style': 'height: 6em;' }), 'pregunta3': Textarea( attrs={ 'class': u'form-control', 'placeholder': u'Ingrese respuesta ...', 'rows': 10, 'cols': 40, 'style': 'height: 6em;' }), 'pregunta4': Textarea( attrs={ 'class': u'form-control', 'placeholder': u'Ingrese respuesta ...', 'rows': 10, 'cols': 40, 'style': 'height: 6em;' }), 'pregunta5': Textarea( attrs={ 'class': u'form-control', 'placeholder': u'Ingrese respuesta ...', 'rows': 10, 'cols': 40, 'style': 'height: 6em;' }), 'pregunta6': Textarea( attrs={ 'class': u'form-control', 'placeholder': u'Ingrese respuesta ...', 'rows': 10, 'cols': 40, 'style': 'height: 6em;' }), 'proteina': NumberInput( attrs={ 'class': u'form-control', 'placeholder': u'%', 'min': '1', 'max': '100', 'step': '1' }), 'grasas': NumberInput( attrs={ 'class': u'form-control', 'placeholder': u'%', 'min': '1', 'max': '100', 'step': '1' }), 'carbohidratos': NumberInput( attrs={ 'class': u'form-control', 'placeholder': u'%', 'min': '1', 'max': '100', 'step': '1' }), 'dieta': Textarea( attrs={ 'class': u'form-control', 'placeholder': u'Tipo de dieta ...', 'rows': 10, 'cols': 40, 'style': 'height: 6em;' }) } error_messages = { 'lacteos_input': { 'max_length': ("This writer's name is too long."), }, }
def get_form(self, form_class=None): if form_class is None: form_class = self.get_form_class() stage_configurations = self.stage.get_queryset_configurations() form = form_class(**self.get_form_kwargs()) used_arg_names = [] # We want to inject fields into the form for the configurations they've marked as prompt for config in stage_configurations: if config.task_argument and config.task_name != self.task_name: continue if not config.prompt_me_for_input: if config.task_argument: used_arg_names.append(config.key) continue str_config_key = 'configuration_value_for_{}'.format(config.key) if config.data_type == config.BOOLEAN_TYPE: field = BooleanField(widget=Select(choices=((False, 'False'), (True, 'True'))), required=False) field.coerce = lambda x: x == 'True', elif config.data_type == config.NUMBER_TYPE: field = FloatField() else: field = CharField() if config.sensitive_value: field.widget = PasswordInput() if config.task_argument: used_arg_names.append(config.key) field.label = 'Argument value for ' + config.key field.initial = config.value form.fields[str_config_key] = field form.helper.layout.fields.insert( len(form.helper.layout.fields) - 1, str_config_key) task_details = backend.get_task_details(self.stage.project, self.task_name) for arg in task_details[2]: if isinstance(arg, tuple): name, default = arg else: name, default = arg, None if name in used_arg_names: continue str_config_key = 'configuration_value_for_{}'.format(name) field = CharField(label='Argument value for ' + name, initial=default) form.fields[str_config_key] = field form.helper.layout.fields.insert( len(form.helper.layout.fields) - 1, str_config_key) return form
def jet_select2_lookups(field): if hasattr(field, 'field') and \ (isinstance(field.field, ModelChoiceField) or isinstance(field.field, ModelMultipleChoiceField)): qs = field.field.queryset model = qs.model # Define a class to be used to create select2 instance if getattr(field.field, 'autocomplete', True): css_class = 'django-jet-select' if 'class' in field.field.widget.widget.attrs: css_class = '{} {}'.format( css_class, field.field.widget.widget.attrs['class']) field.field.widget.widget.attrs['class'] = css_class if getattr(model, 'autocomplete_search_fields', None) and getattr( field.field, 'autocomplete', True): choices = [] app_label = model._meta.app_label model_name = model._meta.object_name attrs = { 'class': 'django-jet-select ajax', 'data-app-label': app_label, 'data-model': model_name, 'data-ajax--url': reverse('jet:model_lookup') } initial_value = field.value() if hasattr(field, 'field') and isinstance( field.field, ModelMultipleChoiceField): if initial_value: initial_objects = model.objects.filter( pk__in=initial_value) choices.extend([(initial_object.pk, get_model_instance_label(initial_object)) for initial_object in initial_objects]) if isinstance(field.field.widget, RelatedFieldWidgetWrapper): field.field.widget.widget = SelectMultiple(attrs) else: field.field.widget = SelectMultiple(attrs) field.field.choices = choices elif hasattr(field, 'field') and isinstance( field.field, ModelChoiceField): if initial_value: try: initial_object = model.objects.get(pk=initial_value) attrs['data-object-id'] = initial_value choices.append( (initial_object.pk, get_model_instance_label(initial_object))) except model.DoesNotExist: pass if isinstance(field.field.widget, RelatedFieldWidgetWrapper): field.field.widget.widget = Select(attrs) else: field.field.widget = Select(attrs) field.field.choices = choices return field