class PaypalFundForm(forms.Form): budget = MoneyField(required=False) bonus = MoneyField(required=False) def __init__(self, account, *args, **kwargs): super(PaypalFundForm, self).__init__(*args, **kwargs) self.account = account self.fields['budget'].error_messages['min_value'] = 'Ensure budget is greater than or equal to %(limit_value)s' def clean(self): cleaned_data = super(PaypalFundForm, self).clean() budget = cleaned_data["budget"] bonus = cleaned_data["bonus"] if budget.amount < 10: raise forms.ValidationError('Ensure budget is greater than or equal to %s' % Money(10, CAD)) if bonus.amount > budget.amount: raise forms.ValidationError('Ensure budget is greater than bonus') if bonus > self.account.bonus_budget: raise forms.ValidationError('Ensure bonus is lower than or equal to %s' % self.account.bonus_budget) return cleaned_data
class EditSupplierPartForm(HelperForm): """ Form for editing a SupplierPart object """ field_prefix = { 'link': 'fa-link', 'MPN': 'fa-hashtag', 'SKU': 'fa-hashtag', 'note': 'fa-pencil-alt', } single_pricing = MoneyField( label=_('Single Price'), default_currency='USD', help_text=_('Single quantity price'), decimal_places=4, max_digits=19, required=False, ) class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'link', 'note', 'single_pricing', # 'base_cost', # 'multiple', 'packaging', ]
def get_special_field(self, col_guess, row, file_manager): """ Set special fields """ # set quantity field if 'quantity' in col_guess.lower(): return forms.CharField( required=False, widget=forms.NumberInput(attrs={ 'name': 'quantity' + str(row['index']), 'class': 'numberinput', 'type': 'number', 'min': '0', 'step': 'any', 'value': clean_decimal(row.get('quantity', '')), }) ) # set price field elif 'price' in col_guess.lower(): return MoneyField( label=_(col_guess), default_currency=InvenTreeSetting.get_setting('INVENTREE_DEFAULT_CURRENCY'), decimal_places=5, max_digits=19, required=False, default_amount=clean_decimal(row.get('purchase_price', '')), ) # return default return super().get_special_field(col_guess, row, file_manager)
class EditSupplierPartForm(HelperForm): """ Form for editing a SupplierPart object """ field_prefix = { 'link': 'fa-link', 'SKU': 'fa-hashtag', 'note': 'fa-pencil-alt', } single_pricing = MoneyField( label=_('Single Price'), default_currency='USD', help_text=_('Single quantity price'), decimal_places=4, max_digits=19, required=False, ) manufacturer = django.forms.ChoiceField( required=False, help_text=_('Select manufacturer'), choices=[], ) MPN = django.forms.CharField( required=False, help_text=_('Manufacturer Part Number'), max_length=100, label=_('MPN'), ) class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'manufacturer', 'MPN', 'description', 'link', 'note', 'single_pricing', # 'base_cost', # 'multiple', 'packaging', ] def get_manufacturer_choices(self): """ Returns tuples for all manufacturers """ empty_choice = [('', '----------')] manufacturers = [(manufacturer.id, manufacturer.name) for manufacturer in Company.objects.filter(is_manufacturer=True)] return empty_choice + manufacturers def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['manufacturer'].choices = self.get_manufacturer_choices()
def __init__(self, *args, **kwargs): super(DonationForm, self).__init__(*args, **kwargs) if hasattr(self, "amounts"): self.amounts = [(i, i) if type(i) in [int, float] else i for i in self.amounts] donate_widget = MoneyWidget(amount_widget=Select( choices=self.amounts)) self.fields["amount"] = MoneyField(currency_widget=donate_widget)
class PaypalSetupForm(AdvertisingSetupForm): budget = MoneyField(min_value=Money(10, CAD)) bonus = MoneyField(required=False) def clean(self): cleaned_data = super(PaypalSetupForm, self).clean() if 'budget' in cleaned_data: budget = cleaned_data['budget'] else: budget = Money(0, CAD) bonus = cleaned_data['bonus'] if bonus.amount > budget.amount: raise forms.ValidationError('Ensure budget is greater than bonus') if bonus > self.account.bonus_budget: raise forms.ValidationError('Ensure bonus is lower than or equal to %s' % self.account.bonus_budget) return cleaned_data
class OrdemServicoForm(forms.ModelForm): acessorios = forms.MultipleChoiceField( required=False, choices=ACESSORIOS_DISPOSITIVOS, widget=forms.CheckboxSelectMultiple()) tipo_servico = forms.ChoiceField(choices=TIPO_SERVICOS, required=True) descricao = forms.CharField(required=False, max_length=300, widget=forms.Textarea(attrs={ 'class': 'form-control', 'rows': '3' })) status = forms.ChoiceField(choices=STATUS, required=True) hospedagem = forms.CharField(required=False, max_length=4) cliente = forms.ModelChoiceField( queryset=Cliente.objects.all(), empty_label="Selecione um cliente...", widget=forms.Select(attrs={'onchange': 'getDispositivo()'})) dispositivos = forms.ModelChoiceField(empty_label="<-----------", queryset=Dispositivo.objects.all()) orcamento = MoneyField(required=False, default_amount=0, max_digits=10, localize=True, decimal_places=2, default_currency='BRL') # Uma classe inline para fornecer informações adicionais no formulário. class Meta: # Fornecer uma associação entre ModelForm e um modelo model = OrdemServico fields = ('acessorios', 'tipo_servico', 'descricao', 'status', 'cliente', 'dispositivos', 'orcamento', 'hospedagem') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['dispositivos'].queryset = Dispositivo.objects.none() if 'cliente' in self.data: try: cliente_id = int(self.data.get('cliente')) self.fields[ 'dispositivos'].queryset = Dispositivo.objects.filter( cliente_id=cliente_id).order_by('modelo') except (ValueError, TypeError): pass # elif self.instance.pk: self.fields[ 'dispositivos'].queryset = self.instance.cliente.dispositivo_set.order_by( 'modelo')
class PortfolioItemForm(forms.ModelForm): invest_date = forms.DateField() amount = forms.FloatField() price = MoneyField() class Meta: model = PortfolioItem fields = ['currency', 'color'] def __init__(self, *args, **kwargs): super(PortfolioItemForm, self).__init__(*args, **kwargs) self.fields['currency'].queryset = Currency.objects.all() self.fields['color'].queryset = Color.objects.all()
class DepositForm(forms.Form): def __init__(self, *args, **kwargs): self.owner_id = kwargs.pop('owner_id') super().__init__(*args, **kwargs) deposit_or_withdrawal = MoneyField(max_digits=10, decimal_places=2) comment = forms.CharField(max_length=128, required=False) def clean_deposit_or_withdrawal(self): data = self.cleaned_data['deposit_or_withdrawal'] wallet, balance = api.get_balance(self.owner_id) if data.amount < 0 and -data > balance: raise forms.ValidationError(_('Not enough funds')) return data
class BillChangeAdminForm(forms.ModelForm): meta_type = forms.ChoiceField(required=True, choices=(('cash', 'Cash'), ('card', 'Card'))) meta_code = forms.CharField(required=False) meta_url = forms.URLField(required=False) meta_amount = MoneyField(required=False, max_digits=8, decimal_places=4, default_currency='USD') class Meta: model = Bill exclude = ('metadata', ) def __init__(self, *args, **kwargs): instance = kwargs.pop('instance', None) initial = kwargs.pop('initial', {}) if instance is not None and instance.metadata is not None: meta = instance.metadata initial['meta_type'] = meta.get('type') initial['meta_code'] = meta.get('code') initial['meta_url'] = meta.get('url') amount = meta.get('amount') if amount is not None: initial['meta_amount'] = Money(amount=amount, currency='USD') super().__init__(*args, instance=instance, initial=initial, **kwargs) def clean(self): data = super().clean() _type = data.get('meta_type') code = data.get('meta_code') url = data.get('meta_url') amount = data.get('meta_amount') if _type == 'cash': if code or url or not amount: raise ValidationError('For cash payment specify amount only') data['metadata'] = {'type': _type, 'amount': float(amount.amount)} return data if _type == 'card': if amount or (not code and not url): raise ValidationError( 'For card payment use "code" and "url" fields') data['metadata'] = {'type': _type, 'code': code, 'url': url} return data raise ValidationError('Unknown payment type')
class SetupFeaturedForm(forms.ModelForm): regions = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Region.objects.filter(country__code="CA"), required=False) start_time = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y')) end_time = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y')) bonus = MoneyField(required=False) class Meta: model = FeaturedEvent fields = ('start_time', 'end_time', 'all_of_canada', 'regions') def __init__(self, account, *args, **kwargs): super(SetupFeaturedForm, self).__init__(*args, **kwargs) self.account = account def clean(self): cleaned_data = self.cleaned_data all_of_canada = cleaned_data['all_of_canada'] bonus = cleaned_data['bonus'] if 'bonus' in cleaned_data else Money( 0, CAD) regions = cleaned_data['regions'] if not all_of_canada and not regions: raise forms.ValidationError( 'You should choose at least one region') if bonus > self.account.bonus_budget: raise forms.ValidationError( 'Ensure bonus is lower than or equal to %s' % self.account.bonus_budget) return cleaned_data
class BonusCampaignForm(forms.ModelForm): budget = MoneyField() start_time = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), required=False) end_time = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), required=False) class Meta: model = BonusCampaign fields = ('start_time', 'end_time', 'budget', 'apply_to_old_accounts') def clean(self): cleaned_data = self.cleaned_data start_time = cleaned_data["start_time"] end_time = cleaned_data["end_time"] apply_to_old_accounts = cleaned_data["apply_to_old_accounts"] if not apply_to_old_accounts and not (start_time and end_time): raise forms.ValidationError('Start time and end time required') return cleaned_data
class FreeTryForm(forms.Form): bonus_budget = MoneyField()
def __init__(self, *args, **kwargs): # Get FileManager file_manager = None if 'file_manager' in kwargs: file_manager = kwargs.pop('file_manager') if 'row_data' in kwargs: row_data = kwargs.pop('row_data') else: row_data = None super().__init__(*args, **kwargs) def clean(number): """ Clean-up decimal value """ # Check if empty if not number: return number # Check if decimal type try: clean_number = Decimal(number) except InvalidOperation: clean_number = number return clean_number.quantize( Decimal(1)) if clean_number == clean_number.to_integral( ) else clean_number.normalize() # Setup FileManager file_manager.setup() # Create fields if row_data: # Navigate row data for row in row_data: # Navigate column data for col in row['data']: # Get column matching col_guess = col['column'].get('guess', None) # Create input for required headers if col_guess in file_manager.REQUIRED_HEADERS: # Set field name field_name = col_guess.lower() + '-' + str( row['index']) # Set field input box if 'quantity' in col_guess.lower(): self.fields[field_name] = forms.CharField( required=False, widget=forms.NumberInput( attrs={ 'name': 'quantity' + str(row['index']), 'class': 'numberinput', # form-control', 'type': 'number', 'min': '0', 'step': 'any', 'value': clean(row.get('quantity', '')), })) # Create item selection box elif col_guess in file_manager.ITEM_MATCH_HEADERS: # Get item options item_options = [(option.id, option) for option in row['item_options']] # Get item match item_match = row['item_match'] # Set field name field_name = 'item_select-' + str(row['index']) # Set field select box self.fields[field_name] = forms.ChoiceField( choices=[('', '-' * 10)] + item_options, required=False, widget=forms.Select(attrs={ 'class': 'select bomselect', })) # Update select box when match was found if item_match: # Make it a required field: does not validate if # removed using JS function # self.fields[field_name].required = True # Update initial value self.fields[field_name].initial = item_match.id # Optional entries elif col_guess in file_manager.OPTIONAL_HEADERS: # Set field name field_name = col_guess.lower() + '-' + str( row['index']) # Get value value = row.get(col_guess.lower(), '') # Set field input box if 'price' in col_guess.lower(): self.fields[field_name] = MoneyField( label=_(col_guess), default_currency=InvenTreeSetting.get_setting( 'INVENTREE_DEFAULT_CURRENCY'), decimal_places=5, max_digits=19, required=False, default_amount=clean(value), ) else: self.fields[field_name] = forms.CharField( required=False, initial=value, )
class JobMatchingForm(CrispyFormMixin, PostcodeFormMixin, forms.Form): """Form for searching freelancers to help match them to a job. Must be instantiated with a job_request, which will prepopulate the search fields based on the job request's values, and allow the form to know which type of freelancer to search for. """ job_matcher = JobMatcher date = forms.DateField(required=False) SHIFT_CHOICES = tuple([(None, '-- Enter shift --')] + [(value, value.capitalize().replace('_', ' ')) for value in Availability.SHIFTS]) shift = forms.ChoiceField(choices=SHIFT_CHOICES, required=False) client_pay_per_hour = MoneyField(max_digits=5, decimal_places=2, required=False) years_experience = forms.ChoiceField( label='Minimum years of experience', required=False, choices=JobRequest.YEARS_EXPERIENCE_CHOICES) # respect_travel_distance = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): # Set the job request self.job_request = kwargs.pop('job_request') super(JobMatchingForm, self).__init__(*args, **kwargs) amount, currency = self.fields['client_pay_per_hour'].fields self.fields['client_pay_per_hour'].widget = \ Bootstrap3SterlingMoneyWidget( amount_widget=amount.widget, currency_widget=widgets.HiddenInput(attrs={'value': 'GBP'}), attrs={'step': '0.25'}) self.set_initial_based_on_job_request() def set_initial_based_on_job_request(self): "Sets the initial data based on the job request." matcher = self.job_matcher(self.job_request) for name, value in matcher.search_terms.items(): self.fields[name].initial = value def clean(self): super(JobMatchingForm, self).clean() # Ensure both, or neither, of the date / shift fields are set for full_field, empty_field in (('date', 'shift'), ('shift', 'date')): if self.cleaned_data.get(full_field) \ and not self.cleaned_data.get(empty_field): self.add_error( empty_field, 'If you are searching by %s, you ' 'must also provide a %s.' % (full_field, empty_field)) def get_results(self): """Returns the results of a successful search. Should be called after the form has been successfully validated.""" matcher = self.job_matcher(self.job_request, self.cleaned_data) results = matcher.get_results() # Also set the freelancer_pay_per_hour on the form self.freelancer_pay_per_hour = getattr(matcher, 'freelancer_pay_per_hour', None) return results
class CorrectionForm(forms.Form): balance = MoneyField(label='Balance', min_value=0) comment = forms.CharField(label='Comment', max_length=128, required=False)