class EditOrderForm(Bootstrap3Form): status = fields.ChoiceField(choices=Order.status_in_choices, label='Статус', widget=forms.RadioSelect, required=True) prepay = fields.FloatField(label='Сумма предоплаты', required=True) relay_free = fields.FloatField(label='Сумма оплаты за пересылку') total = fields.FloatField(label='Итоговая сумма', required=True) type_of_dispatch = fields.ChoiceField(choices=Order.dispatch, label='Тип отправления', widget=forms.Select, required=True) track_number = fields.CharField(label='Номер для отслеживания', min_length=0, max_length=20, required=False) linked_orders = fields.CharField(label='Связанные заказы', min_length=0, max_length=100, required=False)
class ShippingMethodForm(DialogForm): scope_prefix = 'data.shipping_method' shipping_modifier = fields.ChoiceField( label=_("Shipping Method"), widget=widgets.RadioSelect(attrs={'ng-change': 'upload()'}), ) def __init__(self, *args, **kwargs): choices = [ m.get_choice() for m in cart_modifiers_pool.get_shipping_modifiers() if not m.is_disabled(kwargs['cart']) ] self.base_fields['shipping_modifier'].choices = choices if len(choices) == 1: # with only one choice, initialize with it try: kwargs['initial']['shipping_modifier'] = choices[0][0] except KeyError: pass super(ShippingMethodForm, self).__init__(*args, **kwargs) def has_choices(self): return len(self.base_fields['shipping_modifier'].choices) > 0 @classmethod def form_factory(cls, request, data, cart): cart.update(request) shipping_method_form = cls(data=data, cart=cart) if shipping_method_form.is_valid(): cart.extra.update(shipping_method_form.cleaned_data) return shipping_method_form
class PaymentMethodForm(DialogForm): scope_prefix = 'data.payment_method' payment_modifier = fields.ChoiceField( label=_("Payment Method"), widget=widgets.RadioSelect(attrs={'ng-change': 'upload()'}), ) def __init__(self, *args, **kwargs): choices = [ m.get_choice() for m in cart_modifiers_pool.get_payment_modifiers() if not m.is_disabled(kwargs['cart']) ] self.base_fields['payment_modifier'].choices = choices if len(choices) == 1: # if there is only one shipping method available, always set it as default try: kwargs['initial']['payment_modifier'] = choices[0][0] except KeyError: pass super(PaymentMethodForm, self).__init__(*args, **kwargs) def has_choices(self): return len(self.base_fields['payment_modifier'].choices) > 0 @classmethod def form_factory(cls, request, data, cart): cart.update(request) payment_method_form = cls(data=data, cart=cart) if payment_method_form.is_valid(): cart.extra.update(payment_method_form.cleaned_data, payment_extra_data=data.get('payment_data', {})) return payment_method_form
class DummyForm(NgModelFormMixin, NgForm): email = fields.EmailField(label='E-Mail') onoff = fields.BooleanField(initial=False, required=True) sex = fields.ChoiceField(choices=(('m', 'Male'), ('f', 'Female')), widget=widgets.RadioSelect) select_multi = fields.MultipleChoiceField(choices=CHOICES) check_multi = fields.MultipleChoiceField( choices=CHOICES, widget=widgets.CheckboxSelectMultiple) hide_me = fields.CharField(widget=widgets.HiddenInput) scope_prefix = 'dataroot' def __init__(self, *args, **kwargs): kwargs.update(auto_id=False, ng_class='fieldClass(\'%(identifier)s\')', scope_prefix=self.scope_prefix) super(DummyForm, self).__init__(*args, **kwargs) self.sub1 = SubForm1(prefix='sub1', **kwargs) self.sub2 = SubForm2(prefix='sub2', **kwargs) def get_initial_data(self): data = super(DummyForm, self).get_initial_data() data.update({ self.sub1.prefix: self.sub1.get_initial_data(), self.sub2.prefix: self.sub2.get_initial_data(), }) return data def is_valid(self): if not self.sub1.is_valid(): self.errors.update(self.sub1.errors) if not self.sub2.is_valid(): self.errors.update(self.sub2.errors) return super( DummyForm, self).is_valid() and self.sub1.is_valid() and self.sub2.is_valid()
class RadioForm(NgModelFormMixin, NgForm): scope_prefix = 'form_data' sex = fields.ChoiceField( choices=[('m', 'Male'), ('f', 'Female')], widget=widgets.RadioSelect, required=True,)
class ChemicalForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3FormMixin, NgModelForm): # class ChemicalForm(forms.ModelForm): scope_prefix = 'chemical' form_name = 'chemical_form' cas_number = ngfields.CharField( label="CAS Number (SDS § 1)", required=False, widget=forms.TextInput(attrs={'placeholder': 'eg. 7732-18-5'})) formula = ngfields.CharField( label="Formula (SDS § 3)", required=False, # widget=forms.TextInput(attrs={'placeholder': 'eg. H_2O', 'ow-formula': 'ow-formula'}) ) ghs_hazards = ngfields.ModelMultipleChoiceField( label="GHS Hazards (SDS § 2)", # widget=forms.SelectMultiple(attrs={'ow-form': 'chemical_form'}), queryset=models.Hazard.objects.all(), required=False) health = ngfields.ChoiceField(label="Health NFPA Rating (SDS § 15 or 16)", choices=NFPA_RATINGS) flammability = ngfields.ChoiceField( label="Flammability NFPA Rating (SDS § 15 or 16)", choices=NFPA_RATINGS) instability = ngfields.ChoiceField( label="Instability NFPA Rating (SDS § 15 or 16)", choices=NFPA_RATINGS) special_hazards = ngfields.ChoiceField( label="Special Hazards (SDS § 15 or 16)", choices=NFPA_HAZARDS, required=False) gloves = ngfields.ModelMultipleChoiceField( label="Gloves (SDS § 8.2)", queryset=models.Glove.objects.all()) safety_data_sheet = ngfields.FileField( label="Safety Data Sheet (MSDS)", widget=forms.FileInput( attrs={'file-model': 'chemical.safety_data_sheet'}), required=False) class Meta: model = models.Chemical fields = [ 'name', 'cas_number', 'formula', 'ghs_hazards', 'health', 'flammability', 'instability', 'special_hazards', 'gloves', 'safety_data_sheet' ]
class PaymentMethodForm(DialogForm): # from 2nd element of prefix used, always in response after 'data' # is assigned using `$rootScope.data = response.data;` scope_prefix = 'data.payment_method' payment_modifier = fields.ChoiceField( label=_("Payment Method"), widget=widgets.RadioSelect( renderer=ValueInsertRenderer, attrs={ 'ng-change': 'upload()', 'ng-disabled': "$root.data.payment_method.choices.indexOf('$value$') === -1" }), ) def __init__(self, *args, **kwargs): choices = [ m.get_choice() for m in cart_modifiers_pool.get_payment_modifiers() if not m.is_disabled(kwargs['cart']) ] self.base_fields['payment_modifier'].choices = choices if len(choices) == 1: # if there is only one shipping method available, always set it as default try: kwargs['initial']['payment_modifier'] = choices[0][0] except KeyError: pass super(PaymentMethodForm, self).__init__(*args, **kwargs) def has_choices(self): return len(self.base_fields['payment_modifier'].choices) > 0 @classmethod def form_factory(cls, request, data, cart): cart.update(request) payment_method_form = cls(data=data, cart=cart) if payment_method_form.is_valid(): cart.extra.update(payment_method_form.cleaned_data, payment_extra_data=data.get('payment_data', {})) return payment_method_form def get_response_data(self): """ Override default that returns nothing. Add 'choices' payment modifier list for dynamic client-side disable Must match the __init__ choices, otherwise validation will differ between server & client """ choices = [ choice[0] for choice in self.base_fields['payment_modifier'].choices ] return {'choices': choices}
class SearchForm_(Bootstrap3Form): BASE_CHOICES = [('egrul', 'ЕГРЮЛ'), ('egrip', 'ЕГРИП')] ACTIVE_CHOICES = [ ('', 'Все'), ('False', 'Деятельность юридического лица прекращена'), ('True', 'Действующее юридическое лицо или код статуса юридического лица по справочнику СЮЛСТ больше 200 и меньше 700' ), ] # base = fields.ChoiceField(label='Выберите реестр', initial='egrul', choices=BASE_CHOICES) search = fields.CharField( min_length=2, label='ОГРН, ИНН или наименование юридического лица', required=True, error_messages={ "invalid": "Доложно быть заполнено, минимум 2 символа" }) fio = fields.CharField( min_length=2, label= 'ФИО лица, являющегося руководителем, учредителем или участником ЮЛ', required=False, error_messages={ "invalid": "Доложно быть заполнено, минимум 2 символа" }) reg_start_date = fields.DateField(label='Дата начала постановки на учет:', required=False, input_formats=['%Y-%m-%d']) reg_end_date = fields.DateField(label='Дата окончания постановки на учет:', required=False, input_formats=['%Y-%m-%d']) #region = fields.ChoiceField(initial='', label='Регион', choices=REGION_CHOICES) region = fields.ModelChoiceField(empty_label='Любой', label='Регион', to_field_name='КодРегион', queryset=Regions.objects.all()) isactive = fields.ChoiceField(initial='', label='Прекращение деятельности', choices=ACTIVE_CHOICES) #state = fields.ChoiceField(initial='', label='Cостояние (статус) юридического лица', choices=STATE_CHOICES) state = fields.ModelChoiceField( empty_label='Любое', label='Cостояние (статус) юридического лица', to_field_name='КодСтатусЮЛ', queryset=States.objects.all()) okved = fields.ModelChoiceField( empty_label='Любое', label='Наименование вида деятельности по ОКВЭД', to_field_name='КодОКВЭД', queryset=OKVED.objects.all())
class GetOrderingForm_(Bootstrap3Form): TYPES_CHOICES = [('fo', 'Получение выписки, содержащей открытые сведения'), ('fz', 'Получение выписки, содержащей закрытые сведения')] type = fields.ChoiceField(initial='fz', label='Выберите тип запроса', choices=TYPES_CHOICES) search = fields.CharField( min_length=13, label='ОГРН юридического лица', required=True, error_messages={"invalid": "Параметр не является ОГРН"})
class PaymentMethodForm(DialogForm): scope_prefix = 'payment_method' payment_modifier = fields.ChoiceField( label=_("Payment Method"), widget=RadioSelect(attrs={'ng-change': 'updateMethod()'}), ) def __init__(self, *args, **kwargs): choices = [ m.get_choice() for m in cart_modifiers_pool.get_payment_modifiers() ] self.base_fields['payment_modifier'].choices = choices if len(choices) == 1: # if there is only one shipping method available, always set it as default try: kwargs['initial']['payment_modifier'] = choices[0][0] except KeyError: pass super(PaymentMethodForm, self).__init__(*args, **kwargs) def has_choices(self): return len(self.base_fields['payment_modifier'].choices) > 0 @classmethod def form_factory(cls, request, data, cart): cart.update(request) active_mod = data['payment_modifier'] if data[ 'payment_modifier'] is not None else cart.extra['payment_modifier'] current_payment_cart_modifier = cart_modifiers_pool.get_active_payment_modifier( active_mod) payment_method_form = cls(data=data, cart=cart) city = cart.shipping_address.city try: if current_payment_cart_modifier.is_disabled(cart): payment_method_form.add_error( 'payment_modifier', _('Select a valid Payment method. Is not one of the available choices.' )) except: pass if payment_method_form.is_valid(): payment_data = data.get('payment_data') or {} cart.extra.update(payment_method_form.cleaned_data, payment_extra_data=payment_data) return payment_method_form
class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3Form): scope_prefix = 'subscribe_data' form_name = 'subscribe_form' use_required_attribute = False sex = fields.ChoiceField( choices=[('m', 'Male'), ('f', 'Female')], widget=widgets.RadioSelect, error_messages={'invalid_choice': 'Please select your sex'}, ) full_name = fields.CharField( label='Full name', validators=[validate_full_name], help_text='Must consist of a first- and a last name', ) def clean(self): if self.cleaned_data.get('full_name', '').lower() == 'john doe': raise ValidationError( 'The full name "John Doe" is rejected by the server.') return super(SubscribeForm, self).clean()
class RadioForm(NgFormValidationMixin, NgForm): sex = fields.ChoiceField( choices=[('m', 'Male'), ('f', 'Female')], widget=widgets.RadioSelect, required=True, )
class SubscribeForm(NgFormValidationMixin, Bootstrap3Form): use_required_attribute = False CONTINENT_CHOICES = [('am', 'America'), ('eu', 'Europe'), ('as', 'Asia'), ('af', 'Africa'), ('au', 'Australia'), ('oc', 'Oceania'), ('an', 'Antartica')] TRAVELLING_BY = [('foot', 'Foot'), ('bike', 'Bike'), ('mc', 'Motorcycle'), ('car', 'Car'), ('public', 'Public Transportation'), ('train', 'Train'), ('air', 'Airplane')] NOTIFY_BY = [('email', 'EMail'), ('phone', 'Phone'), ('sms', 'SMS'), ('postal', 'Postcard')] first_name = fields.CharField(label='First name', min_length=3, max_length=20) last_name = fields.RegexField( r'^[A-Z][a-z -]?', label='Last name', error_messages={'invalid': 'Last names shall start in upper case'}) sex = fields.ChoiceField( choices=(('m', 'Male'), ('f', 'Female')), widget=widgets.RadioSelect, error_messages={'invalid_choice': 'Please select your sex'}) email = fields.EmailField(label='E-Mail', required=True, help_text='Please enter a valid email address') subscribe = fields.BooleanField(label='Subscribe Newsletter', initial=False, required=False) phone = fields.RegexField( r'^\+?[0-9 .-]{4,25}$', label='Phone number', error_messages={ 'invalid': 'Phone number have 4-25 digits and may start with +' }) birth_date = fields.DateField( label='Date of birth', widget=widgets.DateInput( attrs={'validate-date': '^(\d{4})-(\d{1,2})-(\d{1,2})$'}), help_text='Allowed date format: yyyy-mm-dd') continent = fields.ChoiceField( label='Living on continent', choices=CONTINENT_CHOICES, error_messages={'invalid_choice': 'Please select your continent'}) weight = fields.IntegerField( label='Weight in kg', min_value=42, max_value=95, error_messages={'min_value': 'You are too lightweight'}) height = fields.FloatField( label='Height in meters', min_value=1.48, max_value=1.95, step=0.05, error_messages={'max_value': 'You are too tall'}) traveling = fields.MultipleChoiceField( label='Traveling by', choices=TRAVELLING_BY, help_text='Choose one or more carriers', required=True) notifyme = fields.MultipleChoiceField( label='Notify by', choices=NOTIFY_BY, widget=widgets.CheckboxSelectMultiple, required=True, help_text='Must choose at least one type of notification') annotation = fields.CharField(label='Annotation', required=True, widget=widgets.Textarea(attrs={ 'cols': '80', 'rows': '3' })) agree = fields.BooleanField(label='Agree with our terms and conditions', initial=False, required=True) password = fields.CharField(label='Password', widget=widgets.PasswordInput, validators=[validate_password], help_text='The password is "secret"') confirmation_key = fields.CharField(max_length=40, required=True, widget=widgets.HiddenInput(), initial='hidden value')
class AdvancedSearchForm_(Bootstrap3Form): EDUMETODCODE_CHOICES = [ ('', 'Любой'), ('01', 'Создание юридического лица до 01.07.2002'), ('02', 'Создание юридического лица путем реорганизации до 01.07.2002'), ('03', 'Регистрации на территории Республики Крым или территории города федерального значения Севастополя на день принятия в Российскую Федерацию ' ), ('11', 'Создание юридического лица'), ('21', 'Создание юридического лица путем реорганизации в форме преобразования' ), ('22', 'Создание юридического лица путем реорганизации в форме слияния'), ('23', 'Создание юридического лица путем реорганизации в форме разделения'), ('24', 'Создание юридического лица путем реорганизации в форме выделения'), ('26', 'Создание юридического лица путем реорганизации в форме выделения с одновременным прекращением его деятельности в связи с присоединением к другому юридическому лицу' ), ('29', 'СОЗДАНИЕ ЮРИДИЧЕСКОГО ЛИЦА ПУТЕМ РЕОРГАНИЗАЦИИ В ФОРМЕ СЛИЯНИЯ ЮРИДИЧЕСКИХ ЛИЦ, ВКЛЮЧАЯ ЮРИДИЧЕСКОЕ ЛИЦО, ДЕЯТЕЛЬНОСТЬ КОТОРОГО ПРЕКРАЩАЕТСЯ ОДНОВРЕМЕННО С ЕГО СОЗДАНИЕМ ПРИ РЕОРГАНИЗАЦИИ ДРУГОГО ЮРИДИЧЕСКОГО ЛИЦА В ФОРМЕ РАЗДЕЛЕНИЯ' ), ('30', 'Создание юридического лица путем реорганизации'), ] isaddr = fields.BooleanField( help_text='Сведения об адресе (месте нахождения)', required=False) isAddrFalsity = fields.BooleanField( help_text='Признак недостоверности адреса', required=False) isAddrChange = fields.BooleanField( help_text= 'Сведения о принятии юридическим лицом решения об изменении места нахождения', required=False) index = fields.CharField( required=False, widget=widgets.TextInput(attrs={'placeholder': 'Индекс'})) codeKLADR = fields.CharField( required=False, widget=widgets.TextInput(attrs={'placeholder': 'Код адреса по КЛАДР'})) area = fields.CharField( required=False, widget=widgets.TextInput(attrs={'placeholder': 'Район (улус и т.п.)'})) city = fields.CharField( required=False, widget=widgets.TextInput( attrs={'placeholder': 'Город (волость и т.п.)'})) locality = fields.CharField( required=False, widget=widgets.TextInput( attrs={'placeholder': 'Населенный пункт (село и т.п.)'})) street = fields.CharField( required=False, widget=widgets.TextInput( attrs={'placeholder': 'Улица (проспект, переулок и т.п.)'})) isemail = fields.BooleanField( help_text='Сведения об адресе электронной почты юридического лица', required=False) email = fields.CharField( required=False, widget=widgets.TextInput(attrs={'placeholder': 'E-mail'})) isRegInfo = fields.BooleanField( help_text='Сведения о регистрации (образовании) юридического лица ', required=False) regNum = fields.CharField( required=False, widget=widgets.TextInput( attrs={'placeholder': 'Номер, присвоенный ЮЛ до 1 июля 2002 года' })) codeEduMethod = fields.ChoiceField( initial='', label='Способ образования юридического лица', choices=EDUMETODCODE_CHOICES, widget=widgets.Select(attrs={'class': 'form-control-sm'}))