class PointForm(ModelForm): latitude = DecimalField(max_digits=22, decimal_places=16, required=False, label="Latitude") longitude = DecimalField(max_digits=22, decimal_places=16, required=False, label="Longitude") name = CharField(max_length=180, required=False, label="Name") address1 = CharField(max_length=255, required=False, label="Address1") address2 = CharField(max_length=255, required=False, label="Address2") city = CharField(max_length=180, required=False, label="City") state = CharField(max_length=20, required=False, label="State") zip_code = CharField(max_length=20, required=False, label="Zip code") class Meta: model = Point def save(self, commit=True): super(PointForm, self).save(commit=commit) meta = getattr(self, "Meta", None) if meta: model = getattr(meta, "model", False) if model: if not model.latitude and not model.longitude: model.geocode() else: model.normalize() model.link_postal_code()
def test_decimalfield_scientific(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('1E+2'), decimal.Decimal('1E+2')) self.assertEqual(f.clean('1e+2'), decimal.Decimal('1E+2')) with self.assertRaisesMessage(ValidationError, "Ensure that there are no more"): f.clean('0.546e+2')
class LeForm(Form): def clean_sex2(self): sex2 = self.cleaned_data['sex2'] if sex2 == '': return None else: return sex2 def clean(self): cleaned_data = super(LeForm, self).clean() if self._errors: return cleaned_data sex2 = cleaned_data.get('sex2') age2 = cleaned_data.get('age2') if sex2 == None and age2 != None or sex2 != None and age2 == None: raise ValidationError('Invalid spouse/partner.') return cleaned_data sex = ChoiceField(choices=(('male', 'male'), ('female', 'female'))) age = DecimalField( widget=TextInput(attrs={'class': 'small_numeric_input'}), min_value=0, max_value=110) sex2 = ChoiceField(choices=(('', 'none'), ('male', 'male'), ('female', 'female')), required=False) age2 = DecimalField( widget=TextInput(attrs={'class': 'small_numeric_input'}), min_value=0, max_value=110, required=False)
class ProgForm(ModelForm): versa_sn = ModelChoiceField(queryset=Versa.objects.filter(sn__gt=0), required=True) sw_ver = CharField(required=True) timing_sys_ver = CharField(required=True) voltage = DecimalField(required=True) current = DecimalField(required=True) def __init__(self, *args, **kwargs): super(ProgForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'asmb-form' self.helper.form_method = 'post' self.helper.add_input( Submit('submit', 'Submit', css_class='btn-success')) self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( HTML("""<h2>Programming Form</h2>"""), Fieldset('Versasync Serial Number', Field('versa_sn')), Fieldset( 'Software Versions', Field('sw_ver', placeholder=' software version'), Field('timing_sys_ver', placeholder=' timing system version')), Fieldset('Measured Values', Field('voltage', placeholder=' Voltage'), Field('current', placeholder=' Current'))) class Meta: model = ProgEntry fields = ['versa_sn', 'sw_ver', 'timing_sys_ver', 'voltage', 'current']
class OrderFormUpdate(BSModalForm): date = DateTimeField(widget=DateTimePicker(options={ 'useCurrent': True, 'collapse': False, }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, })) commission = DecimalField(required=False, max_digits=6, min_value=0) price = DecimalField(required=False, min_value=0) def __init__(self, *args, **kwargs): super(OrderFormUpdate, self).__init__(*args, **kwargs) self.fields['price'].required = True self.fields['commission'].required = True self.fields['size'].required = True self.fields['date'].required = True class Meta: model = Orders fields = ['stock', 'date', 'size', 'price', 'commission'] def save(self): my_order = super(CreateUpdateAjaxMixin, self).save() return my_order
class PlaceJobForm(ModelForm): round_trip = BooleanField(label = ("Round Trip"), required = False) time_frame = IntegerField(label = ("Choose Service")) pick_company = CharField(label = ("Pickup Company")) pick_name = CharField(label = ("Contact")) pick_address = CharField(label = ("Pickup Address")) pick_phone = CharField(label = ("Pickup Phone")) pick_email = EmailField(label = ("Pickup Email"), required = False) drop_company = CharField(label = ("Dropoff Company")) drop_name = CharField(label = ("Contact")) drop_address = CharField(label = ("Dropoff Address")) drop_phone = CharField(label = ("Dropoff Phone")) drop_email = EmailField(label = ("Dropoff Email"), required = False) instructions = CharField(label = ("Special Instructions"), required = False) package_type = CharField(label = ("Description")) size = DecimalField(label = ("How Big")) quantity = IntegerField(label = ("How Many")) weight = DecimalField(label = ("How Heavy")) class Meta: model = Job fields = ['round_trip', 'time_frame', 'pick_company', 'pick_name', 'pick_address', 'pick_phone', 'pick_email', 'drop_company', 'drop_name', 'drop_address', 'drop_phone', 'drop_email', 'instructions', 'package_type', 'size', 'quantity', 'weight']
def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): # choices does not make sense in this context, it would mean we had # to replace two widgets with one widget dynamically... which is a # mess. Instead, we let currency_choices be the same as choices and # raise a warning. if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices amount_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) currency_field = ChoiceField(choices=choices) if VERSION < (1, 10) and hasattr(amount_field, '_has_changed') and hasattr(currency_field, '_has_changed'): amount_field.has_changed = amount_field._has_changed currency_field.has_changed = currency_field._has_changed # TODO: No idea what currency_widget is supposed to do since it doesn't # even receive currency choices as input. Somehow it's supposed to be # instantiated from outside. Hard to tell. if currency_widget: self.widget = currency_widget else: self.widget = MoneyWidget( amount_widget=amount_field.widget, currency_widget=currency_field.widget ) # The two fields that this widget comprises fields = (amount_field, currency_field) super(MoneyField, self).__init__(fields, *args, **kwargs)
def test_decimalfield_scientific(self): f = DecimalField(max_digits=4, decimal_places=2) with self.assertRaisesMessage(ValidationError, "Ensure that there are no more"): f.clean('1E+2') self.assertEqual(f.clean('1E+1'), decimal.Decimal('10')) self.assertEqual(f.clean('1E-1'), decimal.Decimal('0.1')) self.assertEqual(f.clean('0.546e+2'), decimal.Decimal('54.6'))
def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): # choices does not make sense in this context, it would mean we had # to replace two widgets with one widget dynamically... which is a # mess. Instead, we let currency_choices be the same as choices and # raise a warning. if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices # get the default currency if one was specified default_currency = kwargs.pop('default_currency', None) validators = [] if min_value: validators.append(MinValueValidator(min_value)) if max_value: validators.append(MaxValueValidator(max_value)) amount_field = DecimalField(max_digits=max_digits, decimal_places=decimal_places, validators=validators, *args, **kwargs) currency_field = ChoiceField(choices=choices) if VERSION < (1, 8) and hasattr(amount_field, '_has_changed') and hasattr( currency_field, '_has_changed'): amount_field.has_changed = amount_field._has_changed currency_field.has_changed = currency_field._has_changed # TODO: No idea what currency_widget is supposed to do since it doesn't # even receive currency choices as input. Somehow it's supposed to be # instantiated from outside. Hard to tell. if currency_widget: self.widget = currency_widget else: self.widget = MoneyWidget(amount_widget=amount_field.widget, currency_widget=currency_field.widget, default_currency=default_currency) # The two fields that this widget comprises fields = (amount_field, currency_field) super(MoneyField, self).__init__(fields, *args, **kwargs) # set the initial value to the default currency so that the # default currency appears as the selected menu item self.initial = [None, default_currency]
def test_decimalfield_2(self): f = DecimalField(max_digits=4, decimal_places=2, required=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertEqual(f.clean('1'), decimal.Decimal("1")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value)
class NewOrderForm(DocboxFormMixin, Form): name = CharField( label="Заказчик", max_length=64, error_messages={"required": "Пожалуйста, введите имя заказчика."}, widget=TextInput({"class": "js-typeahead", "autofocus": True}), ) phone = CharField( label="Телефон", max_length=10, required=False, widget=TextInput({"type": "tel"}), validators=[validate_phone], ) town = CharField(label="Населенный пункт", max_length=64, required=False) street_type = ChoiceField(choices=Address.STREET_TYPES, initial="street", required=False) street = CharField(label="Название", max_length=64, required=False) building = CharField(label="д.", max_length=8, required=False) apartment = IntegerField(label="кв", min_value=0, required=False, widget=TextInput()) total = DecimalField( label="Сумма", max_digits=10, decimal_places=0, error_messages={ "required": "Введите сумму заказа.", "invalid": "Сумма должна состоять только из цифр.", }, widget=TextInput({"class": "text-right"}), ) advance_amount = DecimalField( label="Аванс", max_digits=10, decimal_places=0, required=False, widget=TextInput({"class": "text-right"}), ) comment = CharField(label="Комментарий", max_length=1024, required=False, widget=Textarea({"rows": 3})) def save(self): data = self.cleaned_data client, created = Client.objects.get_or_create(name=data["name"], phone=data["phone"]) address = Address.objects.create( town=data["town"], street_type=data["street_type"], street=data["street"], building=data["building"], apartment=data["apartment"], ) price = Price.objects.create(total=data["total"]) order = Order.objects.create(client=client, address=address, price=price, comment=data["comment"]) if data["advance_amount"]: Transaction.objects.get_or_create(amount=data["advance_amount"], client=client, order=order)
def test_decimalfield_changed(self): f = DecimalField(max_digits=2, decimal_places=2) d = decimal.Decimal("0.1") self.assertFalse(f.has_changed(d, '0.10')) self.assertTrue(f.has_changed(d, '0.101')) with translation.override('fr'), self.settings(USE_L10N=True): f = DecimalField(max_digits=2, decimal_places=2, localize=True) localized_d = formats.localize_input(d) # -> '0,1' in French self.assertFalse(f.has_changed(d, localized_d))
def test_decimalfield_3(self): f = DecimalField(max_digits=4, decimal_places=2, max_value=decimal.Decimal('1.5'), min_value=decimal.Decimal('0.5')) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" required />', ) with self.assertRaisesMessage( ValidationError, "'Ensure this value is less than or equal to 1.5.'"): f.clean('1.6') with self.assertRaisesMessage( ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): f.clean('0.4') self.assertEqual(f.clean('1.5'), decimal.Decimal("1.5")) self.assertEqual(f.clean('0.5'), decimal.Decimal("0.5")) self.assertEqual(f.clean('.5'), decimal.Decimal("0.5")) self.assertEqual(f.clean('00.50'), decimal.Decimal("0.50")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, decimal.Decimal('1.5')) self.assertEqual(f.min_value, decimal.Decimal('0.5'))
def test_enter_a_number_error(self): f = DecimalField(max_value=1, max_digits=4, decimal_places=2) values = ( '-NaN', 'NaN', '+NaN', '-sNaN', 'sNaN', '+sNaN', '-Inf', 'Inf', '+Inf', '-Infinity', 'Infinity', '+Infinity', 'a', 'łąść', '1.0a', '--0.12', ) for value in values: with self.subTest(value=value), self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean(value)
def test_enter_a_number_error(self): f = DecimalField(max_digits=4, decimal_places=2) values = ( '-NaN', 'NaN', '+NaN', '-sNaN', 'sNaN', '+sNaN', '-Inf', 'Inf', '+Inf', '-Infinity', 'Infinity', '+Infinity', 'a', 'łąść', '1.0a', '--0.12', ) for value in values: with self.subTest(value=value), self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean(value)
def test_decimalfield_widget_attrs(self): f = DecimalField(max_digits=6, decimal_places=2) self.assertEqual(f.widget_attrs(Widget()), {}) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '0.01'}) f = DecimalField(max_digits=10, decimal_places=0) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '1'}) f = DecimalField(max_digits=19, decimal_places=19) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '1e-19'}) f = DecimalField(max_digits=20) self.assertEqual(f.widget_attrs(NumberInput()), {'step': 'any'}) f = DecimalField(max_digits=6, widget=NumberInput(attrs={'step': '0.01'})) self.assertWidgetRendersTo(f, '<input step="0.01" name="f" type="number" id="id_f" required />')
class DbForm(Form): def clean(self): cleaned_data = super(AllocBaseForm.DbForm, self).clean() if cleaned_data['social_security']: if not cleaned_data['inflation_indexed']: raise ValidationError( 'Social Security must be inflation indexed') if cleaned_data['joint_type'] == 'contingent': raise ValidationError( 'Social Security death benefit must be survivor') return cleaned_data def __init__(self, data=None, *args, **kwargs): super(AllocBaseForm.DbForm, self).__init__(*args, data=data, **kwargs) if self.data[ self.prefix + '-social_security'] == 'True' if self.is_bound else self.initial[ 'social_security']: self.fields['inflation_indexed'].widget.attrs[ 'readonly'] = True self.fields['joint_type'].widget.attrs['readonly'] = True social_security = BooleanField(required=False, widget=HiddenInput()) description = ChoiceField(choices=(('Pension', 'Pension'), ('Income annuity', 'Income annuity'), ('Reverse mortgage', 'Reverse mortgage'), ('Other', 'Other')), required=False) who = ChoiceField(choices=(('self', ''), ('spouse', '')), widget=HorizontalRadioRenderer) age = DecimalField( widget=TextInput(attrs={'class': 'small_numeric_input'}), min_value=0, max_value=110) amount = DecimalField(widget=TextInput(attrs={'class': 'p_input'}), min_value=0) inflation_indexed = BooleanField(required=False) joint_type = ChoiceField(choices=( ('contingent', ''), ('survivor', ''), ), widget=HorizontalRadioRenderer) joint_payout_pct = DecimalField( widget=TextInput(attrs={'class': 'percent_input'}), min_value=0, max_value=100)
def __init__(self, user_object, *args, **kwargs): # Added user_object argument to __init__ ! super(AccountForm, self).__init__(*args, **kwargs) user_object = user_object self.fields = { } # Otherwise a field will appear for each field in the model, but we want a specific field to show for each Account for account in Account.objects.filter( user=user_object).order_by('account'): if account.active: # Get the last value for the account. If it's None, make placeholder value 0 last_value = 0 if AccountUpdate.objects.filter( account=account).order_by('-timestamp').first( ) is None else AccountUpdate.objects.filter( account=account).order_by('-timestamp').first().value self.fields[account.account] = DecimalField( label=account.account, max_digits=9, decimal_places=2, localize=False, widget=NumberInput( attrs={ 'class': 'form-control form-control-sm', 'style': 'width:180px', 'inputmode': 'decimal', 'placeholder': '${:20,.2f}'.format(last_value) }))
def __init__(self, *args, **kwargs): self.is_sell = kwargs.pop('sell') self.max_size = kwargs.pop('max_size') self.stock_id = kwargs.pop('stock_id') if self.stock_id is not None: del self.base_fields['stock'] self.portfolio_id = kwargs.pop('portfolio_id') super(OrderForm, self).__init__(*args, **kwargs) self.fields['price'].required = True self.fields['commission'].required = True self.fields['date'].required = True if self.stock_id is not None: self.fields['size'] = DecimalField(required=True, max_digits=6, min_value=0, max_value=self.max_size) else: self.fields['size'] = DecimalField(required=True, max_digits=6, min_value=0)
class ColdStorageSend(Form): amount = DecimalField(label=_("AMOUNT")) def __init__(self, *args, **kwargs): self.asset = kwargs.pop("asset") am = control.get_manager(self.asset) super(ColdStorageSend, self).__init__(*args, **kwargs) self.fields["amount"].initial = 0.0 self.fields["amount"].decimal_places = am.decimal_places def clean_amount(self): am = control.get_manager(self.asset) amount = am.quantize(self.cleaned_data["amount"]) # check max amount if amount > am.get_wallet_balance(): raise ValidationError(_("INSUFFICIENT_HOT_FUNDS")) # cold storage wallet exists coldstorages = ColdStorage.objects.filter(asset=self.asset) coldstorages = filter(lambda cs: cs.imported == False, coldstorages) if len(coldstorages) == 0: raise ValidationError(_("ERROR_NO_COLD_STORAGE")) return amount
class CreditPledgeForm(Form): id = IntegerField(required=False, widget=HiddenInput()) pledge_title = CharField( required=False, max_length=512, widget=TextInput(attrs={'class': 'form-control input-sm'})) pledge_type = ChoiceField( required=False, widget=Select(attrs={'class': 'form-control input-sm'}), choices=[ (consts.CREDIT_PLEDGE_TYPE_DEPOSIT, 'Депозит'), (consts.CREDIT_PLEDGE_TYPE_REAL_ESTATE, 'Недвижимость'), (consts.CREDIT_PLEDGE_TYPE_OTHER, 'Другое'), ]) cost = DecimalField( decimal_places=2, required=False, localize=True, widget=TextInput(attrs={'class': 'form-control input-sm'})) DELETE = BooleanField(required=False, widget=CheckboxInput(attrs={'class': 'hidden'})) def get_pledge_type_display(self): for val, val_name in self.fields['pledge_type'].choices: if val == self.initial.get('pledge_type', None): return val_name return '' class Media(object): js = formset_media_js
class PedidoForm(ModelForm): # produto = CharField(widget=HiddenInput()) quantidade = IntegerField(min_value=1,label="Quantidade", help_text="Você deve colocar a quantidade desse produto que deseja.") preco_unit = DecimalField(min_value=0,label="Preço Unitário", help_text="Valor que deseja pagar por unidade.") class Meta: model = Pedido # fields = "__all__" fields = ('preco_unit','quantidade',) def clean_preco_unit(self): valor = self.cleaned_data.get("preco_unit") if valor >= (float(self.produto.preco_unit) - float(self.produto.preco_unit) * 0.1): return valor else: raise forms.ValidationError("Esse produto deve ser vendido igual ou acima de R$ %s" % (float(self.produto.preco_unit) - float(self.produto.preco_unit) * 0.1)) def clean_quantidade(self): quantidade = self.cleaned_data.get("quantidade") if quantidade % self.produto.multiplo == 0 : return quantidade else: raise forms.ValidationError("Esse produto só pode ser vendido por multiplos de %s" %self.produto.multiplo) def __init__(self, *args, **kwargs): if 'id' in kwargs: produto_id = kwargs.pop('id') self.produto = Produto.objects.get(id=produto_id) super(PedidoForm, self).__init__(*args, **kwargs) self.fields['quantidade'].initial = self.produto.multiplo self.fields['preco_unit'].initial = self.produto.preco_unit
def __init__(self, *args, **kwargs): steps = kwargs.pop('steps') super(MCPriorityForm, self).__init__(*args, **kwargs) for step, value in steps: self.fields['custom_%s' % step] = DecimalField(label=step, required=True) if value: self.data['custom_%s' % step] = value
def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=DECIMAL_PLACES, default_amount=None, default_currency=None, *args, **kwargs): amount_field = DecimalField(*args, max_value=max_value, min_value=min_value, max_digits=max_digits, decimal_places=decimal_places, **kwargs) currency_field = ChoiceField(choices=currency_choices) self.widget = MoneyWidget( amount_widget=amount_field.widget, currency_widget=currency_widget or currency_field.widget, default_currency=default_currency, ) # The two fields that this widget comprises fields = (amount_field, currency_field) super().__init__(fields, *args, **kwargs) # set the initial value to the default currency so that the # default currency appears as the selected menu item self.initial = [default_amount, default_currency]
class WorkoutLogForm(ModelForm): """ Helper form for a WorkoutLog. These fields are re-defined here only to make them optional. Otherwise all the entries in the formset would be required, which is not really what we want. This form is one prime candidate to rework with some modern JS framework, there is a ton of ugly logic like this just to make it work. """ repetition_unit = ModelChoiceField(queryset=RepetitionUnit.objects.all(), label=_('Unit'), required=False) weight_unit = ModelChoiceField(queryset=WeightUnit.objects.all(), label=_('Unit'), required=False) exercise = ModelChoiceField(queryset=Exercise.objects.all(), label=_('Exercise'), required=False) reps = IntegerField(label=_('Repetitions'), required=False) weight = DecimalField(label=_('Weight'), initial=0, required=False) rir = ChoiceField(label=_('RiR'), choices=RIR_OPTIONS, required=False) class Meta: model = WorkoutLog exclude = ('workout', )
class UserAPIPutForm(Form): username = CharField() password = CharField(widget=PasswordInput) role = CharField() name = CharField() balance = DecimalField(max_digits=15, decimal_places=2) profile = CharField(required=False)
def test_decimalfield_localized(self): """ A localized DecimalField's widget renders to a text input without number input specific attributes. """ f = DecimalField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required>')
class ExemplaireVenteForm(ModelForm): exclude = ( 'actif', 'livre', 'etat', ) isbn = CharField(required=True, help_text="Scannez le code barre du livre", label="ISBN", max_length=13) titre = CharField(required=True, label="Titre", help_text="Titre") identifiant = IntegerField(required=True, label="Identifiant", help_text="Identifiant", widget=IdentifiantTextInput) auteur = CharField(required=True, label="Auteur", help_text="Auteur") prix = DecimalField(required=True, label="Prix demandé", help_text="Prix") def clean(self): cleaned_data = super(ExemplaireVenteForm, self).clean() self.instance = Exemplaire.objects.get(pk=cleaned_data['identifiant']) self.instance.etat = 'VEND' self.instance.save() return cleaned_data class Meta: model = Exemplaire
class TransactionAddForm(MoneypitForm): type = ChoiceField(choices=Transaction.TYPES) description = CharField(required=False) amount = DecimalField(initial=0.0) date = DateField(initial=datetime.utcnow()) def __init__(self, *args, **kwargs): self.wealth = kwargs.pop('wealth', None) self.accounts_list = kwargs.pop('accounts_list', None) super(TransactionAddForm, self).__init__(*args, **kwargs) self.fields['account_from'] = ChoiceField(choices=self.accounts_list) def clean_account_from(self): return self._check_account('account_from', 'The transaction account does not exist') def clean_amount(self): return self._check_amount('amount') def _check_account(self, field, error_msg): account_id = self.cleaned_data[field] try: Account.objects.get(id=account_id, wealth=self.wealth) except ObjectDoesNotExist: raise ValidationError(error_msg) return account_id def _check_amount(self, field): amount = self.cleaned_data[field] if amount and amount <= 0: raise ValidationError('Amount cannot be negative') return amount
class SearchFormTest(Form): # TODO: Create a field for ModelChoiceField STATUS_CHOICES = [ ('', 'All'), (True, 'Active'), (False, 'Inactive') ] field1 = CharField() field2 = TextInput() field3 = ChoiceField(choices=STATUS_CHOICES) field4 = BooleanField() field5 = DateField() field6 = DateTimeField() field7 = FloatField() field8 = DecimalField() field9 = IntegerField() field90 = CharField() field91 = CharField() def __init__(self, *args, **kwargs): super(SearchFormTest, self).__init__(*args, **kwargs) self.fields['field90'].label = "Date Start" self.fields['field91'].label = "Date End"
class TimecardAdminForm(ModelForm): billable_expectation = DecimalField( initial=settings.DEFAULT_BILLABLE_EXPECTATION) class Meta: model = Timecard fields = '__all__'
class _LineMultipleAddForm(core_forms.CremeForm): quantity = DecimalField( label=_('Quantity'), min_value=constants.DEFAULT_DECIMAL, initial=constants.DEFAULT_QUANTITY, decimal_places=2, ) discount_value = DecimalField( label=_('Discount'), min_value=constants.DEFAULT_DECIMAL, max_value=Decimal('100'), initial=constants.DEFAULT_DECIMAL, decimal_places=2, help_text=_('Percentage applied on the unit price'), ) vat = ModelChoiceField( label=_('Vat'), queryset=Vat.objects.all(), empty_label=None, ) def _get_line_class(self): raise NotImplementedError def __init__(self, entity, *args, **kwargs): # super(_LineMultipleAddForm, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs) self.billing_document = entity self.fields['vat'].initial = Vat.get_default_vat( ) # Not in field declaration because default value can change def save(self): cdata = self.cleaned_data create_item = partial( self._get_line_class().objects.create, related_document=self.billing_document, quantity=cdata['quantity'], discount=cdata['discount_value'], vat_value=cdata['vat'], ) for item in cdata['items']: create_item( related_item=item, unit_price=item.unit_price, unit=item.unit, )
class PatchForm(ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(PatchForm, self).__init__(*args, **kwargs) box = ModelChoiceField(label='box', queryset=Box.objects.all(), widget=HiddenInput()) garden = ModelChoiceField(label='garden', queryset=Garden.objects.all(), widget=HiddenInput()) recorded = DateField( label='recorded', widget=HiddenInput(), ) crop = ModelChoiceField( label='Crop name', queryset=Crop.objects.filter(needs_moderation=False), error_messages={ 'required': "Please enter a crop name.", }, widget=AddNewCropWidget(), ) crop_variety = VarietyField( queryset=Variety.objects.filter(needs_moderation=False), required=False, ) quantity = DecimalField( max_value=Decimal('1000'), min_value=Decimal('0.1'), max_digits=5, decimal_places=2, error_messages={ 'invalid': "Please enter a number for the quantity.", 'min_value': "Please enter a non-negative number.", 'max_value': "Please enter a smaller number.", 'max_digits': "Please enter a smaller number.", 'max_whole_digits': "Please enter a smaller number (%d digits).", 'max_decimal_places': ("Please enter a number with at most %d " "decimal places."), }, widget=TextInput(attrs={ 'size': 6, 'maxlength': 6 }), ) units = ChoiceField(choices=Patch.UNITS_CHOICES, ) added_by = ModelChoiceField(label='added_by', queryset=get_user_model().objects.all(), widget=HiddenInput()) class Meta: model = Patch exclude = ('added', 'updated')
class BigTimeCorrectionForm(forms.Form): date = DateField(widget=forms.DateInput(format="%M/%D"), label="What day did you come in (MM/DD)?") hours = DecimalField(min_value=0, max_value=12, max_digits=4, decimal_places=2, label="How many hours did you do?")
class OrderForm(BSModalForm): date = DateTimeField( widget=DateTimePicker( options={ 'useCurrent': True, 'collapse': False, }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ) ) commission = DecimalField(required=False, max_digits=6, min_value=0) price = DecimalField(required=False, min_value=0) def __init__(self, *args, **kwargs): self.is_sell = kwargs.pop('sell') self.max_size = kwargs.pop('max_size') self.stock_id = kwargs.pop('stock_id') if self.stock_id is not None: del self.base_fields['stock'] self.portfolio_id = kwargs.pop('portfolio_id') super(OrderForm, self).__init__(*args, **kwargs) self.fields['price'].required = True self.fields['commission'].required = True self.fields['date'].required = True if self.stock_id is not None: self.fields['size'] = DecimalField(required=True, max_digits=6, min_value=0, max_value=self.max_size) else: self.fields['size'] = DecimalField(required=True, max_digits=6, min_value=0) class Meta: model = Orders fields = ['date', 'size', 'price', 'commission', 'stock'] def clean(self): self.instance.portfolio_id = self.portfolio_id if self.stock_id is not None: self.instance.stock_id = self.stock_id if self.is_sell: self.instance.size = int(self.data['size']) * -1 return super(OrderForm, self).clean()
def test_decimalfield_5(self): f = DecimalField(max_digits=3) # Leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('0000000.10'), decimal.Decimal("0.1")) # But a leading 0 before the . doesn't count towards max_digits self.assertEqual(f.clean('0000000.100'), decimal.Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('000000.02'), decimal.Decimal('0.02')) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'"): f.clean('000000.0002') self.assertEqual(f.clean('.002'), decimal.Decimal("0.002"))
def test_decimalfield_3(self): f = DecimalField( max_digits=4, decimal_places=2, max_value=decimal.Decimal('1.5'), min_value=decimal.Decimal('0.5') ) self.assertWidgetRendersTo(f, '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" />') with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"): f.clean('1.6') with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): f.clean('0.4') self.assertEqual(f.clean('1.5'), decimal.Decimal("1.5")) self.assertEqual(f.clean('0.5'), decimal.Decimal("0.5")) self.assertEqual(f.clean('.5'), decimal.Decimal("0.5")) self.assertEqual(f.clean('00.50'), decimal.Decimal("0.50")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, decimal.Decimal('1.5')) self.assertEqual(f.min_value, decimal.Decimal('0.5'))
def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), decimal.Decimal(".01")) msg = "'Ensure that there are no more than 0 digits before the decimal point.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1.1')
def test_decimalfield_4(self): f = DecimalField(decimal_places=2) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): f.clean('0.00000001')
def test_decimalfield_support_decimal_separator(self): f = DecimalField(localize=True) self.assertEqual(f.clean('1001,10'), decimal.Decimal("1001.10")) self.assertEqual(f.clean('1001.10'), decimal.Decimal("1001.10"))
def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) self.assertWidgetRendersTo(f, '<input id="id_f" step="0.01" type="number" name="f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(f.clean('1'), decimal.Decimal("1")) self.assertIsInstance(f.clean('1'), decimal.Decimal) self.assertEqual(f.clean('23'), decimal.Decimal("23")) self.assertEqual(f.clean('3.14'), decimal.Decimal("3.14")) self.assertEqual(f.clean(3.14), decimal.Decimal("3.14")) self.assertEqual(f.clean(decimal.Decimal('3.14')), decimal.Decimal("3.14")) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('NaN') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('Inf') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('-Inf') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('a') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('łąść') self.assertEqual(f.clean('1.0 '), decimal.Decimal("1.0")) self.assertEqual(f.clean(' 1.0'), decimal.Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), decimal.Decimal("1.0")) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('1.0a') with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): f.clean('123.45') with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): f.clean('1.234') msg = "'Ensure that there are no more than 2 digits before the decimal point.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('123.4') self.assertEqual(f.clean('-12.34'), decimal.Decimal("-12.34")) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): f.clean('-123.45') self.assertEqual(f.clean('-.12'), decimal.Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), decimal.Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), decimal.Decimal("-0.12")) with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): f.clean('-000.123') with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): f.clean('-000.12345') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('--0.12') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value)
def test_decimalfield_support_thousands_separator(self): f = DecimalField(localize=True) self.assertEqual(f.clean('1.001,10'), decimal.Decimal("1001.10")) msg = "'Enter a number.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1,001.1')