class coco2(forms.Form): size = forms.FloatField() sh = forms.CharField(widget=forms.Select(choices=Choises_coco))
class QuadraticForm(forms.Form): a = forms.FloatField(widget=forms.TextInput(attrs={'class': 'number'}), label='a', max_value=100000, min_value=-100000) b = forms.FloatField(widget=forms.TextInput(attrs={'class': 'number'}), label='b', max_value=100000, min_value=-100000) c = forms.FloatField(widget=forms.TextInput(attrs={'class': 'number'}), label='c', max_value=100000, min_value=-100000)
class pinForm(forms.Form): Distance_from_left = forms.FloatField()
class DoorAmountForm(forms.Form): ''' This is the form that staff users fill out to indicate that they received a cash payment. Upon this being marked, the registration is processed. ''' submissionUser = forms.ModelChoiceField(queryset=User.objects.filter( Q(staffmember__isnull=False) | Q(is_staff=True)), required=True) paid = forms.BooleanField(label=_('Payment Received'), required=False) receivedBy = forms.ModelChoiceField( queryset=User.objects.filter( Q(staffmember__isnull=False) | Q(is_staff=True)), label=_('Payment received by:'), required=False, widget=autocomplete.ModelSelect2( url='autocompleteUser', attrs={ # This will set the input placeholder attribute: 'data-placeholder': _('Enter a user name'), # This will set the yourlabs.Autocomplete.minimumCharacters # options, the naming conversion is handled by jQuery 'data-autocomplete-minimum-characters': 2, 'data-widget-maximum-values': 4, 'class': 'modern-style', })) amountPaid = forms.FloatField(label=_('Amount Paid'), required=False) invoiceSent = forms.BooleanField(label=_('Send Invoice'), required=False) cashPayerEmail = forms.EmailField(label=_('Payer Email Address'), required=False) invoicePayerEmail = forms.EmailField(label=_('Payer Email Address'), required=False) discountAmount = forms.FloatField(required=False) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) payerEmail = kwargs.pop('payerEmail', None) doorPortion = kwargs.pop('doorPortion', None) invoicePortion = kwargs.pop('invoicePortion', None) discountAmount = kwargs.pop('discountAmount', None) subUser = getattr(user, 'id', None) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_tag = False # Our template must explicitly include the <form tag> if doorPortion: door_layout = Layout( HTML(""" <div class="panel panel-default"> <div class="panel-heading" role="tab" id="door_headingOne"> <h4 class="panel-title"> """ + str(_('Cash Payment')) + """ </h4> </div> <div class="panel-body"> """), 'paid', 'receivedBy', 'amountPaid', 'cashPayerEmail', Submit('submit', 'Submit'), HTML(""" </div> </div> """), ) else: door_layout = Layout(HTML("")) if invoicePortion: invoice_layout = Layout( HTML(""" <div class="panel panel-default"> <div class="panel-heading" role="tab" id="door_headingTwo"> <h4 class="panel-title"> """ + str(_('Send Invoice')) + """ </h4> </div> <div class="panel-body"> """), 'invoiceSent', 'invoicePayerEmail', Hidden('discountAmount', discountAmount), Submit('submit', 'Submit'), HTML(""" </div> </div> """), ) else: invoice_layout = Layout(HTML("")) self.helper.layout = Layout( HTML( '<div class="panel-group" id="door_accordion" role="tablist" aria-multiselectable="true">' ), Hidden('submissionUser', subUser), door_layout, invoice_layout, HTML('</div>')) kwargs.update( initial={ 'cashPayerEmail': payerEmail, 'invoicePayerEmail': payerEmail, 'receivedBy': subUser, }) super(DoorAmountForm, self).__init__(*args, **kwargs) def clean_submissionUser(self): paid = self.data.get('paid') or None invoiceSent = self.data.get('invoiceSent') or None user_id = self.data.get('submissionUser') or None if user_id: user = User.objects.get(id=user_id) if not user_id or not user: raise ValidationError(_('submissionUser not found.')) elif paid and not user.has_perm('core.accept_door_payments'): raise ValidationError(_('Invalid user submitted door payment.')) elif invoiceSent and not user.has_perm('core.send_invoices'): raise ValidationError(_('Invalid user submitted invoice.')) return user def clean(self): form_data = self.cleaned_data logger.debug('Form Data:\n%s' % form_data) paid = form_data.get('paid') invoiceSent = form_data.get('invoiceSent') if paid and invoiceSent: raise ValidationError( _('Must choose either cash payment or invoice submission, not both.' )) if not paid and not invoiceSent: raise ValidationError( _('Must select either cash payment or invoice submission.')) # Check for required values here because the form can be used in two ways. if paid: if not form_data.get('submissionUser'): raise ValidationError(_('Submission user is required.')) if not form_data.get('receivedBy'): raise ValidationError( _('Must specify recipient of the money.')) if not form_data.get('amountPaid'): raise ValidationError( _('Must specify the amount of the payment.')) if invoiceSent: if not form_data.get('submissionUser'): raise ValidationError(_('Submission user is required.')) if not form_data.get('invoicePayerEmail'): raise ValidationError( _('Must specify the email address of the invoice recipient.' )) return form_data
class CalculateDensity(forms.Form): salinity = forms.FloatField(min_value=0.0, max_value=42.0) temperature = forms.FloatField(min_value=-2.0, max_value=40.0) pressure = forms.FloatField(min_value=0.0, max_value=10000.0)
class ChangeKegForm(forms.Form): keg_size = forms.ChoiceField(choices=keg_sizes.CHOICES, initial=keg_sizes.HALF_BARREL, required=True) initial_volume = forms.FloatField(label='Initial Volume', initial=0.0, required=False, help_text='Keg\'s Initial Volume') beer_name = forms.CharField(required=False) # legacy brewer_name = forms.CharField(required=False) # legacy beverage_name = forms.CharField(label='Beer Name', required=False) beverage_id = forms.CharField(widget=forms.HiddenInput(), required=False) producer_name = forms.CharField(label='Brewer', required=False) producer_id = forms.CharField(widget=forms.HiddenInput(), required=False) style_name = forms.CharField(required=True, label='Style', help_text='Example: Pale Ale, Stout, etc.') helper = FormHelper() helper.form_class = 'form-horizontal beer-select' helper.layout = Layout( Field('beverage_name', css_class='input-xlarge'), Field('beverage_id', type='hidden'), Field('producer_name', css_class='input-xlarge'), Field('producer_id', type='hidden'), Field('style_name', css_class='input-xlarge'), Field('keg_size', css_class='input-xlarge'), Field('initial_volume', css_class='input-volume'), FormActions( Submit('submit_change_keg_form', 'Activate Keg', css_class='btn-primary'), )) def clean_beverage_name(self): beverage_name = self.cleaned_data.get('beverage_name') if not beverage_name: beverage_name = self.cleaned_data.get('beer_name') if not beverage_name: raise forms.ValidationError('Must specify a beverage name') self.cleaned_data['beverage_name'] = beverage_name return beverage_name def clean_producer_name(self): producer_name = self.cleaned_data.get('producer_name') if not producer_name: producer_name = self.cleaned_data.get('brewer_name') if not producer_name: raise forms.ValidationError('Must specify a producer name') self.cleaned_data['producer_name'] = producer_name return producer_name def save(self, tap): if not self.is_valid(): raise ValueError('Form is not valid.') b = get_kegbot_backend() if tap.is_active(): b.end_keg(tap.current_keg) keg_size = self.cleaned_data.get('keg_size') full_volume_ml = self.cleaned_data.get('full_volume_ml') if keg_size != 'other': full_volume_ml = None else: full_volume_ml = self.cleaned_data.get('initial_volume') # TODO(mikey): Support non-beer beverage types. cd = self.cleaned_data keg = b.start_keg(tap, beverage_name=cd['beverage_name'], producer_name=cd['producer_name'], beverage_type='beer', style_name=cd['style_name'], keg_type=cd['keg_size'], full_volume_ml=full_volume_ml) if cd.get('description'): keg.description = cd['description'] keg.save()
class ContactForm(forms.Form): cellname = forms.CharField() cellid1 = forms.CharField() cellomcname = forms.CharField() province = forms.CharField() city = forms.CharField() district = forms.CharField() villages = forms.CharField() enodebid = forms.CharField() cellid2 = forms.CharField() sector = forms.CharField() eutranCellid = forms.CharField() factory = forms.CharField() villagestypes = forms.CharField() mr = forms.CharField() lon = forms.FloatField() lat = forms.FloatField() antennaid = forms.CharField() antennanum = forms.IntegerField() worktypes = forms.CharField() cp = forms.CharField() subframe = forms.CharField() specificsubframe = forms.CharField() remoterru = forms.CharField() upfpoint = forms.FloatField() downfpoint = forms.FloatField() pci = forms.IntegerField(max_value=550) pcilist = forms.CharField() cellmaxpower = forms.FloatField() rspower = forms.CharField() atypepower1 = forms.CharField() btypepower1 = forms.CharField() atypepower2 = forms.CharField() btypepower2 = forms.CharField() bcchpower = forms.FloatField() maxpower = forms.FloatField() tac = forms.IntegerField() taclist = forms.CharField(required=False) operation = forms.CharField() updatatime = forms.CharField() coveragetypes = forms.CharField() coveragerange = forms.CharField() plmn = forms.CharField() mbms = forms.CharField(required=False) band = forms.IntegerField() centerfrequency = forms.CharField() bandwidth = forms.CharField() downCyclicPrefix = forms.CharField() upCyclicPrefix = forms.CharField() upbandwidth = forms.CharField() downbandwidth = forms.CharField() astat = forms.CharField() hs = forms.CharField(required=False) txrxmod = forms.CharField() worktypes1 = forms.CharField() leadingformat = forms.CharField(required=False) isblocking = forms.CharField(required=False) boundarycell = forms.CharField(required=False) boundaryname = forms.CharField(required=False) csbf = forms.CharField() hs2 = forms.CharField(required=False) istelecom = forms.CharField() build = forms.CharField() sharingmode = forms.CharField() isca = forms.CharField() catypes = forms.CharField() catypeassociation = forms.CharField() camaincellid = forms.CharField() customize1 = forms.CharField() customize2 = forms.CharField() customize3 = forms.CharField() customize4 = forms.CharField() customize5 = forms.CharField() customize6 = forms.CharField() customize7 = forms.CharField() customize8 = forms.CharField() customize9 = forms.CharField(required=False) customize10 = forms.CharField(required=False) rruid = forms.CharField() rruname = forms.CharField() bbuid = forms.CharField() physicalstationid = forms.CharField() rrutypes = forms.CharField() rruport = forms.CharField() txrxtypes = forms.CharField() antennaid_1 = forms.CharField() antennaid1 = forms.CharField() rruid_1 = forms.CharField(required=False) directionangle = forms.FloatField() antennaheight = forms.FloatField() electricaldowntilt = forms.CharField() mechanicaltilt = forms.CharField() antennatypes = forms.CharField() beautifytypes = forms.CharField() antennafactory = forms.CharField() antennamodel = forms.CharField() antennanum_1 = forms.CharField() horizontalpowerangle = forms.CharField() verticalpowerangle = forms.CharField() antennagain = forms.CharField() picture1 = forms.CharField() picture2 = forms.CharField() picture3 = forms.CharField() picture4 = forms.CharField() towermast = forms.CharField() txrxmod_1 = forms.CharField() verticalrange = forms.CharField() install = forms.CharField(required=False) scenesid = forms.CharField() networktype = forms.CharField() def make_clean(self, cleam_data): # cleam_data={'name':'coveragetypes','mapping':COVER_TYPElist,} cleam = self.cleaned_data[cleam_data['name']] if cleam not in cleam_data['mapping'].viewkeys(): raise forms.ValidationError(u'不在有效数据范围之内') return cleam def clean_coveragetypes(self): cleam_data = { 'name': 'coveragetypes', 'mapping': COVER_TYPElist, } return self.make_clean(cleam_data) def clean_city(self): cleam_data = { 'name': 'city', 'mapping': CITYID, } return self.make_clean(cleam_data) def clean_villagestypes(self): cleam_data = { 'name': 'villagestypes', 'mapping': ADMIN_REGIONSlist, } return self.make_clean(cleam_data) def clean_district(self): cleam_data = { 'name': 'district', 'mapping': DISTRICT_ID, } return self.make_clean(cleam_data) def clean_mr(self): cleam_data = { 'name': 'mr', 'mapping': IS_Mrlist, } return self.make_clean(cleam_data) def clean_worktypes(self): cleam_data = { 'name': 'worktypes', 'mapping': DUP_MODElist, } return self.make_clean(cleam_data) def clean_remoterru(self): cleam_data = { 'name': 'remoterru', 'mapping': RRUCELL_FLAGlist, } return self.make_clean(cleam_data) def clean_astat(self): cleam_data = { 'name': 'astat', 'mapping': CELL_ACTIVE_STATElist, } return self.make_clean(cleam_data) def clean_hs(self): cleam_data = { 'name': 'hs', 'mapping': HIGH_SPEED_FLAGlist, } return self.make_clean(cleam_data) def clean_txrxmod(self): cleam_data = { 'name': 'txrxmod', 'mapping': TX_RX_MODElist, } return self.make_clean(cleam_data) def clean_csbf(self): cleam_data = { 'name': 'csbf', 'mapping': CSFBlist, } return self.make_clean(cleam_data) def clean_build(self): cleam_data = { 'name': 'build', 'mapping': COMPANYlist, } return self.make_clean(cleam_data) def clean_sharingmode(self): cleam_data = { 'name': 'sharingmode', 'mapping': SHARED_TYPElsit, } return self.make_clean(cleam_data) def clean_factory(self): cleam_data = { 'name': 'factory', 'mapping': VENDOR_Idlsit, } return self.make_clean(cleam_data) def clean_rrutypes(self): cleam_data = { 'name': 'rrutypes', 'mapping': RRU_MODELlist, } return self.make_clean(cleam_data)
class SiteForm(HTML5BootstrapModelForm, KOModelForm): x = forms.FloatField(widget=forms.HiddenInput(), required=False) y = forms.FloatField(widget=forms.HiddenInput(), required=False) width = forms.FloatField(widget=forms.HiddenInput(), required=False) height = forms.FloatField(widget=forms.HiddenInput(), required=False) site_meta_attributes_ans = forms.CharField(widget=forms.HiddenInput(), required=False) def __init__(self, *args, **kwargs): super(SiteForm, self).__init__(*args, **kwargs) if not self.fields['location'].initial: self.fields['location'].initial = Point(85.3240, 27.7172, srid=4326) self.fields['logo'].label = "Image" self.fields['logo'].required = False self.fields['weight'].required = False class Meta: model = Site exclude = ('project', 'is_survey', 'is_active', 'current_status', 'current_progress', 'additional_desc', 'site_featured_images', "site", "all_ma_ans") project_filters = ['type'] widgets = { 'address': forms.TextInput(), # 'location': gform.OSMWidget(attrs={'map_width': 400, 'map_height': 400}), # 'project' : forms.HiddenInput(), 'location': forms.HiddenInput(), 'logo': AdminImageWidget() } def save(self, commit=True, *args, **kwargs): is_new = kwargs.pop('new') if is_new: photo = super(SiteForm, self).save(commit=False) photo.project_id = kwargs.pop('project_id') if 'region_id' in kwargs: photo.region_id = kwargs.pop('region_id') if 'site_id' in kwargs: site = Site.objects.get(pk=kwargs.pop('site_id')) photo.site_id = site.id photo.region_id = site.region_id if site.region else None # metas all if photo.site_meta_attributes_ans: photo.all_ma_ans.update(photo.site_meta_attributes_ans) photo.save() photo = super(SiteForm, self).save() # if else for new and update x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') if x is not None and y is not None: image = Image.open(photo.logo) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) # resized_image.save(photo.logo.path) resized_image_file = StringIO.StringIO() mime = mimetypes.guess_type(photo.logo.name)[0] plain_ext = mime.split('/')[1] resized_image.save(resized_image_file, plain_ext) default_storage.delete(photo.logo.name) default_storage.save(photo.logo.name, ContentFile(resized_image_file.getvalue())) resized_image_file.close() return photo def clean(self): lat = self.data.get("Longitude") long = self.data.get("Latitude") p = Point(round(float(lat), 6), round(float(long), 6), srid=4326) self.cleaned_data["location"] = p super(SiteForm, self).clean()
class CreatePromoForm(forms.Form): email = forms.EmailField() platform_key = forms.CharField(label='Platform Key') value = forms.FloatField(max_value=20000, min_value=0)
class SnaForm(VizBaseForm): theme_list = ( ('default', 'Default'), ('light', 'Light'), ('dark', 'Dark'), ) layouts = ( ('fr', 'Fruchterman Reingold (Spring Layout)'), ('fa2', 'ForceAtlas2'), ) theme = forms.ChoiceField( required=True, choices=theme_list, initial='default', widget=forms.Select(attrs={ 'class': 'form-control', }, ), ) node_num = forms.IntegerField( required=True, label='Number Of Nodes', initial=35, widget=forms.NumberInput(attrs={ 'class': 'form-control', }, ), help_text= 'The number of nodes in the result may be reduced if Remove Isolated Node is ON', ) edge_remove_threshold = forms.IntegerField( required=True, label='Edge Remove Threshold', initial=0, widget=forms.NumberInput(attrs={ 'class': 'form-control', }, ), ) remove_isolated_node = forms.BooleanField( required=False, label='Remove Isolated Node', initial=True, help_text='Default : ON', ) iterations = forms.IntegerField( required=True, initial=50, widget=forms.NumberInput(attrs={'class': 'form-control'}, ), ) layout = forms.ChoiceField( required=True, choices=layouts, initial='fr', widget=forms.Select(attrs={ 'class': 'form-control', }, ), ) fr_k = forms.FloatField( required=True, label='Argument k (Float)', initial=0, widget=forms.NumberInput(attrs={ 'class': 'form-control', 'step': 'any', }, ), help_text='Optimal distance between nodes. 0 equals None', ) fa2_square = forms.IntegerField( required=True, label='Variable Square', initial=2, widget=forms.NumberInput(attrs={ 'class': 'form-control', }, ), ) fa2_log_base = forms.IntegerField( required=True, label='Variable log(base)', initial=100, widget=forms.NumberInput(attrs={ 'class': 'form-control', }, ), ) def clean_data_file(self): uploaded_data = self.cleaned_data['data_file'] if uploaded_data: if uploaded_data.content_type == 'text/plain': data_raw = uploaded_data.read().decode() return data_raw.split('\n') elif uploaded_data.content_type == 'text/csv': data_raw = pd.read_csv(uploaded_data, encoding='CP949', header=None) data = [] for post in data_raw[0]: data.append(post) return data else: self.fields['data_file'].widget.attrs['class'] += ' is-invalid' raise forms.ValidationError( "Uploaded File is not *.txt or *.csv") else: return None def clean_node_num(self): node_num = self.cleaned_data['node_num'] if node_num < 1: self.fields['node_num'].widget.attrs['class'] += ' is-invalid' raise forms.ValidationError("Number of nodes can't be less than 1") return node_num def clean_edge_remove_threshold(self): edge_remove_threshold = self.cleaned_data['edge_remove_threshold'] if edge_remove_threshold < 0: self.fields['edge_remove_threshold'].widget.attrs[ 'class'] += ' is-invalid' raise forms.ValidationError( "Edge Remove Threshold can't be negative") return edge_remove_threshold def clean_iterations(self): iterations = self.cleaned_data['iterations'] if iterations < 0: self.fields['iterations'].widget.attrs['class'] += ' is-invalid' raise forms.ValidationError("Iterations can't be negative") return iterations def clean_fr_k(self): fr_k = self.cleaned_data['fr_k'] if fr_k == 0: fr_k = None elif fr_k < 0: self.fields['fr_k'].widget.attrs['class'] += ' is-invalid' raise forms.ValidationError("k can't be negative") return fr_k def clean_fa2_log_base(self): fa2_log_base = self.cleaned_data['fa2_log_base'] if fa2_log_base < 0 or fa2_log_base == 1: self.fields['fa2_log_base'].widget.attrs['class'] += ' is-invalid' raise forms.ValidationError( "Log base value can't be negative or 1") return fa2_log_base
class ProjectForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput(), required=False) y = forms.FloatField(widget=forms.HiddenInput(), required=False) width = forms.FloatField(widget=forms.HiddenInput(), required=False) height = forms.FloatField(widget=forms.HiddenInput(), required=False) sector = forms.ModelChoiceField(queryset=Sector.objects.filter( sector=None)) sub_sector = forms.ModelChoiceField( queryset=Sector.objects.filter(~Q(sector=None))) def clean_sub_sector(self): cleaned_data = super(ProjectForm, self).clean() if self.instance.id: sub_sector = cleaned_data.get('sub_sector') sector = cleaned_data.get('sector') print(sub_sector.sector) if sub_sector.sector == sector: return sub_sector elif not sub_sector.sector == self.instance.sector: msg = 'Select the sub sector that matches the selected sector' self.add_error('sub_sector', msg) else: msg = 'Select the sub sector that matches the selected sector' self.add_error('sub_sector', msg) else: return cleaned_data.get('sub_sector') def __init__(self, *args, **kwargs): is_new = kwargs.pop('new', None) org_id = kwargs.pop('organization_id', None) super(ProjectForm, self).__init__(*args, **kwargs) if not self.fields['location'].initial: self.fields['location'].initial = Point(85.3240, 27.7172, srid=4326) # self.fields['type'].empty_label = None if self.instance.cluster_sites: self.fields.pop('cluster_sites') else: self.fields[ 'cluster_sites'].label = "Do you want to cluster sites in this Project?" #self.fields['organization'].empty_label = None if not is_new: org_id = kwargs['instance'].organization.id # self.fields['geo_layers'].queryset = GeoLayer.objects.filter( # organization__id=org_id # ) class Meta: model = Project exclude = ('organization', 'is_active', 'site_meta_attributes', 'gsuit_meta', 'geo_layers', 'fax', 'additional_desc', 'type', 'site_basic_info', 'site_featured_images', 'gsuit_sync', 'gsuit_sync_end_of_month', 'gsuit_sync_date') #organization_filters = ['organization'] widgets = { 'is_active': forms.HiddenInput(), 'address': forms.TextInput(), 'location': forms.HiddenInput(), 'logo': AdminImageWidget() } def save(self, commit=True, *args, **kwargs): is_new = kwargs.pop('new') if is_new: photo = super(ProjectForm, self).save(commit=False) photo.organization_id = kwargs.pop('organization_id') photo.save() photo = super(ProjectForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') if x is not None and y is not None: image = Image.open(photo.logo) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) # resized_image.save(photo.logo.path) resized_image_file = StringIO.StringIO() mime = mimetypes.guess_type(photo.logo.name)[0] plain_ext = mime.split('/')[1] resized_image.save(resized_image_file, plain_ext) default_storage.delete(photo.logo.name) default_storage.save(photo.logo.name, ContentFile(resized_image_file.getvalue())) resized_image_file.close() return photo def clean(self): lat = self.data.get("Longitude", "85.3240") long = self.data.get("Latitude", "27.7172") p = Point(round(float(lat), 6), round(float(long), 6), srid=4326) self.cleaned_data["location"] = p super(ProjectForm, self).clean()
class PaymentForm(forms.Form): tid = forms.CharField(max_length=20) reference = forms.CharField(max_length=150) amount = forms.FloatField()
class CoursesForm(forms.Form): c_id = forms.FloatField() is_delete = forms.IntegerField() c_code = forms.CharField(max_length=350) c_name = forms.CharField(max_length=300)
class PublicationForm(forms.Form): is_delete = forms.IntegerField() pub_id = forms.FloatField() authors = forms.CharField(max_length=350) journ_name = forms.CharField(max_length=300) year = forms.IntegerField()
class AcceptForm(forms.Form): garbage_id = forms.CharField() transaction_id = forms.CharField() negotiate_price = forms.FloatField() inquiry_id = forms.CharField()
class ContestSubmissionForm(forms.Form): email = forms.EmailField() platform_key = forms.CharField(label='Platform Key') contest_key = forms.CharField(label='Contest Key') value = forms.FloatField(max_value=20000, min_value=0)
class InquiryAdd(forms.Form): garbage_id = forms.CharField() title = forms.CharField() content = forms.CharField() transaction_id = forms.CharField() negotiate_price = forms.FloatField()
class SendForm(forms.Form): send_to = forms.CharField(label='Dirección destino', max_length=100, validators=[crw_address]) amount = forms.FloatField(label='Cantidad')
class KegForm(forms.Form): keg_size = forms.ChoiceField(choices=keg_sizes.CHOICES, initial=keg_sizes.HALF_BARREL, required=True) initial_volume = forms.FloatField(label='Initial Volume', initial=0.0, required=False, help_text='Keg\'s Initial Volume') beer_name = forms.CharField(required=False) # legacy brewer_name = forms.CharField(required=False) # legacy beverage_name = forms.CharField(label='Beer Name', required=False) beverage_id = forms.CharField(widget=forms.HiddenInput(), required=False) producer_name = forms.CharField(label='Brewer', required=False) producer_id = forms.CharField(widget=forms.HiddenInput(), required=False) style_name = forms.CharField(required=True, label='Style', help_text='Example: Pale Ale, Stout, etc.') description = forms.CharField( max_length=256, label='Description', widget=forms.Textarea(), required=False, help_text='Optional user-visible description of the keg.') notes = forms.CharField( label='Notes', required=False, widget=forms.Textarea(), help_text= 'Optional private notes about this keg, viewable only by admins.') connect_to = forms.ModelChoiceField( queryset=ALL_TAPS, label='Connect To', required=False, help_text='If selected, immediately activates the keg on this tap. ' '(Any existing keg will be ended.)') helper = FormHelper() helper.form_class = 'form-horizontal beer-select' helper.layout = Layout( Field('beverage_name', css_class='input-xlarge'), Field('beverage_id', type='hidden'), Field('producer_name', css_class='input-xlarge'), Field('producer_id', type='hidden'), Field('style_name', css_class='input-xlarge'), Field('keg_size', css_class='input-xlarge'), Field('initial_volume', css_class='input-volume'), Field('description', css_class='input-block-level', rows='3'), Field('notes', css_class='input-block-level', rows='3'), Field('connect_to', css_class='input-block-level'), FormActions(Submit('submit_add_keg', 'Save', css_class='btn-primary'), )) def clean_beverage_name(self): beverage_name = self.cleaned_data.get('beverage_name') if not beverage_name: beverage_name = self.cleaned_data.get('beer_name') if not beverage_name: raise forms.ValidationError('Must specify a beverage name') self.cleaned_data['beverage_name'] = beverage_name return beverage_name def clean_producer_name(self): producer_name = self.cleaned_data.get('producer_name') if not producer_name: producer_name = self.cleaned_data.get('brewer_name') if not producer_name: raise forms.ValidationError('Must specify a producer name') self.cleaned_data['producer_name'] = producer_name return producer_name def save(self): if not self.is_valid(): raise ValueError('Form is not valid.') keg_size = self.cleaned_data.get('keg_size') if keg_size != 'other': full_volume_ml = None else: full_volume_ml = self.cleaned_data.get('initial_volume') # TODO(mikey): Support non-beer beverage types. cd = self.cleaned_data b = get_kegbot_backend() keg = b.create_keg(beverage_name=cd['beverage_name'], producer_name=cd['producer_name'], beverage_type='beer', style_name=cd['style_name'], keg_type=cd['keg_size'], full_volume_ml=full_volume_ml, notes=cd['notes'], description=cd['description']) tap = cd['connect_to'] if tap: if tap.is_active(): b.end_keg(tap.current_keg) b.attach_keg(tap, keg) return keg
class ItemForm(ModelForm): class Meta: model = Item id = forms.IntegerField(required=False) name = forms.CharField(max_length=50, label="Name") short_description = forms.CharField(max_length=100, label="Description") description = forms.CharField(max_length=1000, label="Details") price = forms.FloatField(label="Price") def _is_valid(self): res = ModelForm.is_valid(self) if self.instance.id is None: return res for f in FlagType.objects.all(): fv = self.data[f.name] d = {'item': self.instance.id, 'type': f.id, 'value': fv} try: fg = Flag.objects.get(item=self.instance.id, type=f.id) except Flag.DoesNotExist: continue ff = FlagForm(d, instance=fg) if not ff.is_valid(): res = False self.errors[f.name] = ff.errors return res def get(self, id): res = {} instance = Item.objects.get(id=id) for k in instance._meta.fields: res[k.name] = getattr(instance, k.name) for f in FlagType.objects.all(): try: fg = Flag.objects.get(item=instance.id, type=f.id) res[f.name] = fg.value except Flag.DoesNotExist: continue return res def delete(self, id=None): if id is None: instance = self.instance else: instance = Item.objects.get(id=id) for f in FlagType.objects.all(): try: fg = Flag.objects.get(item=instance.id, type=f.id) except Flag.DoesNotExist: continue fg.delete() instance.delete() def save(self, **args): res = ModelForm.save(self, **args) for f in FlagType.objects.all(): fv = self.data[f.name] d = {'item': self.instance.id, 'type': f.id, 'value': fv} try: fg = Flag.objects.get(item=self.instance.id, type=f.id) except Flag.DoesNotExist: fg = Flag() ff = FlagForm(d, instance=fg) fv = ff.save() setattr(res, f.name, fv) return res for f in FlagType.objects.all(): locals()[f.name] = forms.CharField(max_length=100, label=f.description)
class AcquireNodeForm(RenamableFieldsForm): """A form handling the constraints used to acquire a node.""" name = forms.CharField(label="The hostname of the desired node", required=False) system_id = forms.CharField(label="The system_id of the desired node", required=False) # This becomes a multiple-choice field during cleaning, to accommodate # architecture wildcards. arch = forms.CharField(label="Architecture", required=False) cpu_count = forms.FloatField( label="CPU count", required=False, error_messages={'invalid': "Invalid CPU count: number required."}) mem = forms.FloatField( label="Memory", required=False, error_messages={'invalid': "Invalid memory: number of MiB required."}) tags = UnconstrainedMultipleChoiceField(label="Tags", required=False) not_tags = UnconstrainedMultipleChoiceField(label="Not having tags", required=False) # XXX mpontillo 2015-10-30 need validators for fabric constraints fabrics = ValidatorMultipleChoiceField( validator=lambda x: True, label="Attached to fabrics", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of fabrics required.", }) not_fabrics = ValidatorMultipleChoiceField( validator=lambda x: True, label="Not attached to fabrics", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of fabrics required.", }) fabric_classes = ValidatorMultipleChoiceField( validator=lambda x: True, label="Attached to fabric with specified classes", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of fabric classes required.", }) not_fabric_classes = ValidatorMultipleChoiceField( validator=lambda x: True, label="Not attached to fabric with specified classes", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of fabric classes required." }) subnets = ValidatorMultipleChoiceField( validator=Subnet.objects.validate_filter_specifiers, label="Attached to subnets", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of subnet specifiers required.", }) not_subnets = ValidatorMultipleChoiceField( validator=Subnet.objects.validate_filter_specifiers, label="Not attached to subnets", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of subnet specifiers required.", }) vlans = ValidatorMultipleChoiceField( validator=VLAN.objects.validate_filter_specifiers, label="Attached to VLANs", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of VLAN specifiers required.", }) not_vlans = ValidatorMultipleChoiceField( validator=VLAN.objects.validate_filter_specifiers, label="Not attached to VLANs", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of VLAN specifiers required.", }) connected_to = ValidatorMultipleChoiceField( validator=mac_validator, label="Connected to", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of MAC addresses required." }) not_connected_to = ValidatorMultipleChoiceField( validator=mac_validator, label="Not connected to", required=False, error_messages={ 'invalid_list': "Invalid parameter: list of MAC addresses required." }) zone = forms.CharField(label="Physical zone", required=False) not_in_zone = ValidatorMultipleChoiceField( validator=MODEL_NAME_VALIDATOR, label="Not in zone", required=False, error_messages={ 'invalid_list': "Invalid parameter: must list physical zones.", }) pool = forms.CharField(label="Resource pool", required=False) not_in_pool = ValidatorMultipleChoiceField( validator=MODEL_NAME_VALIDATOR, label="Not in resource pool", required=False, error_messages={ 'invalid_list': "Invalid parameter: must list resource pools.", }) storage = forms.CharField(validators=[storage_validator], label="Storage", required=False) interfaces = LabeledConstraintMapField(validators=[interfaces_validator], label="Interfaces", required=False) ignore_unknown_constraints = False pod = forms.CharField(label="The name of the desired pod", required=False) not_pod = forms.CharField(label="The name of the undesired pod", required=False) pod_type = forms.CharField(label="The power_type of the desired pod", required=False) not_pod_type = forms.CharField(label="The power_type of the undesired pod", required=False) @classmethod def Strict(cls, *args, **kwargs): """A stricter version of the form which rejects unknown parameters.""" form = cls(*args, **kwargs) form.ignore_unknown_constraints = False return form def clean_arch(self): """Turn `arch` parameter into a list of architecture names. Even though `arch` is a single-value field, it turns into a list during cleaning. The architecture parameter may be a wildcard. """ # Import list_all_usable_architectures as part of its module, not # directly, so that patch_usable_architectures can easily patch it # for testing purposes. usable_architectures = maasserver_forms.list_all_usable_architectures() architecture_wildcards = get_architecture_wildcards( usable_architectures) value = self.cleaned_data[self.get_field_name('arch')] if value: if value in usable_architectures: # Full 'arch/subarch' specified directly. return [value] elif value in architecture_wildcards: # Try to expand 'arch' to all available 'arch/subarch' # matches. return architecture_wildcards[value] set_form_error(self, self.get_field_name('arch'), 'Architecture not recognised.') return None def clean_tags(self): value = self.cleaned_data[self.get_field_name('tags')] if value: tag_names = parse_legacy_tags(value) # Validate tags. tag_names = set(tag_names) db_tag_names = set( Tag.objects.filter(name__in=tag_names).values_list('name', flat=True)) if len(tag_names) != len(db_tag_names): unknown_tags = tag_names.difference(db_tag_names) error_msg = 'No such tag(s): %s.' % ', '.join( "'%s'" % tag for tag in unknown_tags) set_form_error(self, self.get_field_name('tags'), error_msg) return None return tag_names return None def clean_zone(self): value = self.cleaned_data[self.get_field_name('zone')] if value: nonexistent_names = detect_nonexistent_names(Zone, [value]) if nonexistent_names: error_msg = "No such zone: '%s'." % value set_form_error(self, self.get_field_name('zone'), error_msg) return None return value return None def clean_not_in_zone(self): value = self.cleaned_data[self.get_field_name('not_in_zone')] if not value: return None nonexistent_names = detect_nonexistent_names(Zone, value) if nonexistent_names: error_msg = "No such zone(s): %s." % ', '.join(nonexistent_names) set_form_error(self, self.get_field_name('not_in_zone'), error_msg) return None return value def clean_pool(self): value = self.cleaned_data[self.get_field_name('pool')] if value: nonexistent_names = detect_nonexistent_names(ResourcePool, [value]) if nonexistent_names: error_msg = "No such pool: '%s'." % value set_form_error(self, self.get_field_name('pool'), error_msg) return None return value return None def clean_not_in_pool(self): value = self.cleaned_data[self.get_field_name('not_in_pool')] if not value: return None nonexistent_names = detect_nonexistent_names(ResourcePool, value) if nonexistent_names: error_msg = "No such pool(s): %s." % ', '.join(nonexistent_names) set_form_error(self, self.get_field_name('not_in_pool'), error_msg) return None return value def _clean_specifiers(self, model, specifiers): if not specifiers: return None objects = set(model.objects.filter_by_specifiers(specifiers)) if len(objects) == 0: raise ValidationError("No matching %s found." % model._meta.verbose_name_plural) return objects def clean_subnets(self): value = self.cleaned_data[self.get_field_name('subnets')] return self._clean_specifiers(Subnet, value) def clean_not_subnets(self): value = self.cleaned_data[self.get_field_name('not_subnets')] return self._clean_specifiers(Subnet, value) def clean_vlans(self): value = self.cleaned_data[self.get_field_name('vlans')] return self._clean_specifiers(VLAN, value) def clean_not_vlans(self): value = self.cleaned_data[self.get_field_name('not_vlans')] return self._clean_specifiers(VLAN, value) def __init__(self, *args, **kwargs): super(AcquireNodeForm, self).__init__(*args, **kwargs) def clean(self): if not self.ignore_unknown_constraints: unknown_constraints = set(self.data).difference( set(self.field_mapping.values())) for constraint in unknown_constraints: if constraint not in IGNORED_FIELDS: msg = "Unable to allocate a machine. No such constraint." self._errors[constraint] = self.error_class([msg]) return super(AcquireNodeForm, self).clean() def describe_constraint(self, field_name): """Return a human-readable representation of a constraint. Turns a constraint value as passed to the form into a Juju-like representation for display: `name=foo`. Multi-valued constraints are shown as comma-separated values, e.g. `tags=do,re,mi`. :param field_name: Name of the constraint on this form, e.g. `zone`. :return: A constraint string, or `None` if the constraint is not set. """ value = self.cleaned_data.get(field_name, None) if value is None: return None if isinstance(self.fields[field_name], MultipleChoiceField): output = describe_multi_constraint_value(value) elif field_name == 'arch' and not isinstance(value, str): # The arch field is a special case. It's defined as a string # field, but may become a list/tuple/... of strings in cleaning. output = describe_multi_constraint_value(value) else: output = describe_single_constraint_value(value) if output is None: return None else: return '%s=%s' % (field_name, output) def describe_constraints(self): """Return a human-readable representation of the given constraints. The description is Juju-like, e.g. `arch=amd64 cpu=16 zone=rack3`. Constraints are listed in alphabetical order. """ constraints = (self.describe_constraint(name) for name in sorted(self.fields.keys())) return ' '.join(constraint for constraint in constraints if constraint is not None) def filter_nodes(self, nodes): """Return the subset of nodes that match the form's constraints. :param nodes: The set of nodes on which the form should apply constraints. :type nodes: `django.db.models.query.QuerySet` :return: A QuerySet of the nodes that match the form's constraints. :rtype: `django.db.models.query.QuerySet` """ filtered_nodes = nodes filtered_nodes = self.filter_by_pod_or_pod_type(filtered_nodes) filtered_nodes = self.filter_by_hostname(filtered_nodes) filtered_nodes = self.filter_by_system_id(filtered_nodes) filtered_nodes = self.filter_by_arch(filtered_nodes) filtered_nodes = self.filter_by_cpu_count(filtered_nodes) filtered_nodes = self.filter_by_mem(filtered_nodes) filtered_nodes = self.filter_by_tags(filtered_nodes) filtered_nodes = self.filter_by_zone(filtered_nodes) filtered_nodes = self.filter_by_pool(filtered_nodes) filtered_nodes = self.filter_by_subnets(filtered_nodes) filtered_nodes = self.filter_by_vlans(filtered_nodes) filtered_nodes = self.filter_by_fabrics(filtered_nodes) filtered_nodes = self.filter_by_fabric_classes(filtered_nodes) compatible_nodes, filtered_nodes = self.filter_by_storage( filtered_nodes) compatible_interfaces, filtered_nodes = self.filter_by_interfaces( filtered_nodes) filtered_nodes = self.reorder_nodes_by_cost(filtered_nodes) return filtered_nodes, compatible_nodes, compatible_interfaces def reorder_nodes_by_cost(self, filtered_nodes): # This uses a very simple procedure to compute a machine's # cost. This procedure is loosely based on how ec2 computes # the costs of machines. This is here to give a hint to let # the call to acquire() decide which machine to return based # on the machine's cost when multiple machines match the # constraints. filtered_nodes = filtered_nodes.distinct().extra( select={'cost': "cpu_count + memory / 1024."}) return filtered_nodes.order_by("cost") def filter_by_interfaces(self, filtered_nodes): compatible_interfaces = {} interfaces_label_map = self.cleaned_data.get( self.get_field_name('interfaces')) if interfaces_label_map is not None: node_ids, compatible_interfaces = nodes_by_interface( interfaces_label_map) if node_ids is not None: filtered_nodes = filtered_nodes.filter(id__in=node_ids) return compatible_interfaces, filtered_nodes def filter_by_storage(self, filtered_nodes): compatible_nodes = {} # Maps node/storage to named storage constraints storage = self.cleaned_data.get(self.get_field_name('storage')) if storage: compatible_nodes = nodes_by_storage(storage) node_ids = list(compatible_nodes) if node_ids is not None: filtered_nodes = filtered_nodes.filter(id__in=node_ids) return compatible_nodes, filtered_nodes def filter_by_fabric_classes(self, filtered_nodes): fabric_classes = self.cleaned_data.get( self.get_field_name('fabric_classes')) if fabric_classes is not None and len(fabric_classes) > 0: filtered_nodes = filtered_nodes.filter( interface__vlan__fabric__class_type__in=fabric_classes) not_fabric_classes = self.cleaned_data.get( self.get_field_name('not_fabric_classes')) if not_fabric_classes is not None and len(not_fabric_classes) > 0: filtered_nodes = filtered_nodes.exclude( interface__vlan__fabric__class_type__in=not_fabric_classes) return filtered_nodes def filter_by_fabrics(self, filtered_nodes): fabrics = self.cleaned_data.get(self.get_field_name('fabrics')) if fabrics is not None and len(fabrics) > 0: # XXX mpontillo 2015-10-30 need to also handle fabrics whose name # is null (fabric-<id>). filtered_nodes = filtered_nodes.filter( interface__vlan__fabric__name__in=fabrics) not_fabrics = self.cleaned_data.get(self.get_field_name('not_fabrics')) if not_fabrics is not None and len(not_fabrics) > 0: # XXX mpontillo 2015-10-30 need to also handle fabrics whose name # is null (fabric-<id>). filtered_nodes = filtered_nodes.exclude( interface__vlan__fabric__name__in=not_fabrics) return filtered_nodes def filter_by_vlans(self, filtered_nodes): vlans = self.cleaned_data.get(self.get_field_name('vlans')) if vlans is not None and len(vlans) > 0: for vlan in set(vlans): filtered_nodes = filtered_nodes.filter(interface__vlan=vlan) not_vlans = self.cleaned_data.get(self.get_field_name('not_vlans')) if not_vlans is not None and len(not_vlans) > 0: for not_vlan in set(not_vlans): filtered_nodes = filtered_nodes.exclude( interface__vlan=not_vlan) return filtered_nodes def filter_by_subnets(self, filtered_nodes): subnets = self.cleaned_data.get(self.get_field_name('subnets')) if subnets is not None and len(subnets) > 0: for subnet in set(subnets): filtered_nodes = filtered_nodes.filter( interface__ip_addresses__subnet=subnet) not_subnets = self.cleaned_data.get(self.get_field_name('not_subnets')) if not_subnets is not None and len(not_subnets) > 0: for not_subnet in set(not_subnets): filtered_nodes = filtered_nodes.exclude( interface__ip_addresses__subnet=not_subnet) return filtered_nodes def filter_by_zone(self, filtered_nodes): zone = self.cleaned_data.get(self.get_field_name('zone')) if zone: zone_obj = Zone.objects.get(name=zone) filtered_nodes = filtered_nodes.filter(zone=zone_obj) not_in_zone = self.cleaned_data.get(self.get_field_name('not_in_zone')) if not_in_zone: not_in_zones = Zone.objects.filter(name__in=not_in_zone) filtered_nodes = filtered_nodes.exclude(zone__in=not_in_zones) return filtered_nodes def filter_by_pool(self, filtered_nodes): pool_name = self.cleaned_data.get(self.get_field_name('pool')) if pool_name: pool = ResourcePool.objects.get(name=pool_name) filtered_nodes = filtered_nodes.filter(pool=pool) not_in_pool = self.cleaned_data.get(self.get_field_name('not_in_pool')) if not_in_pool: pools_to_exclude = ResourcePool.objects.filter( name__in=not_in_pool) filtered_nodes = filtered_nodes.exclude(pool__in=pools_to_exclude) return filtered_nodes def filter_by_tags(self, filtered_nodes): tags = self.cleaned_data.get(self.get_field_name('tags')) if tags: for tag in tags: filtered_nodes = filtered_nodes.filter(tags__name=tag) not_tags = self.cleaned_data.get(self.get_field_name('not_tags')) if len(not_tags) > 0: for not_tag in not_tags: filtered_nodes = filtered_nodes.exclude(tags__name=not_tag) return filtered_nodes def filter_by_mem(self, filtered_nodes): mem = self.cleaned_data.get(self.get_field_name('mem')) if mem: filtered_nodes = filtered_nodes.filter(memory__gte=mem) return filtered_nodes def filter_by_cpu_count(self, filtered_nodes): cpu_count = self.cleaned_data.get(self.get_field_name('cpu_count')) if cpu_count: filtered_nodes = filtered_nodes.filter(cpu_count__gte=cpu_count) return filtered_nodes def filter_by_arch(self, filtered_nodes): arch = self.cleaned_data.get(self.get_field_name('arch')) if arch: filtered_nodes = filtered_nodes.filter(architecture__in=arch) return filtered_nodes def filter_by_system_id(self, filtered_nodes): # Filter by system_id. system_id = self.cleaned_data.get(self.get_field_name('system_id')) if system_id: filtered_nodes = filtered_nodes.filter(system_id=system_id) return filtered_nodes def filter_by_hostname(self, filtered_nodes): # Filter by hostname. hostname = self.cleaned_data.get(self.get_field_name('name')) if hostname: # If the given hostname has a domain part, try matching # against the nodes' FQDN. if "." in hostname: host, domain = hostname.split('.', 1) hostname_clause = Q(hostname=host) domain_clause = Q(domain__name=domain) clause = (hostname_clause & domain_clause) else: clause = Q(hostname=hostname) filtered_nodes = filtered_nodes.filter(clause) return filtered_nodes def filter_by_pod_or_pod_type(self, filtered_nodes): # Filter by pod, pod type, not_pod or not_pod_type. # We are filtering for all of these to keep the query count down. pod = self.cleaned_data.get(self.get_field_name('pod')) not_pod = self.cleaned_data.get(self.get_field_name('not_pod')) pod_type = self.cleaned_data.get(self.get_field_name('pod_type')) not_pod_type = self.cleaned_data.get( self.get_field_name('not_pod_type')) if pod or pod_type or not_pod or not_pod_type: pods = Pod.objects.all() if pod: pods = pods.filter(name=pod) if not pod: pods = pods.exclude(name=not_pod) if pod_type: pods = pods.filter(power_type=pod_type) if not_pod_type: pods = pods.exclude(power_type=not_pod_type) filtered_nodes = filtered_nodes.filter( bmc_id__in=pods.values_list('id', flat=True)) return filtered_nodes
class SQLSelectForm(forms.Form): """ Validate params sql: The sql statement with interpolated params raw_sql: The sql statement with placeholders params: JSON encoded parameter values duration: time for SQL to execute passed in from toolbar just for redisplay hash: the hash of (secret + sql + params) for tamper checking """ sql = forms.CharField() raw_sql = forms.CharField() params = forms.CharField() alias = forms.CharField(required=False, initial='default') duration = forms.FloatField() hash = forms.CharField() def __init__(self, *args, **kwargs): initial = kwargs.get('initial', None) if initial is not None: initial['hash'] = self.make_hash(initial) super(SQLSelectForm, self).__init__(*args, **kwargs) for name in self.fields: self.fields[name].widget = forms.HiddenInput() def clean_raw_sql(self): value = self.cleaned_data['raw_sql'] if not value.lower().strip().startswith('select'): raise ValidationError("Only 'select' queries are allowed.") return value def clean_params(self): value = self.cleaned_data['params'] try: return json.loads(value) except ValueError: raise ValidationError('Is not valid JSON') def clean_alias(self): value = self.cleaned_data['alias'] if value not in connections: raise ValidationError("Database alias '%s' not found" % value) return value def clean_hash(self): hash = self.cleaned_data['hash'] if not constant_time_compare(hash, self.make_hash(self.data)): raise ValidationError('Tamper alert') return hash def reformat_sql(self): return reformat_sql(self.cleaned_data['sql']) def make_hash(self, data): m = hmac.new(key=force_bytes(settings.SECRET_KEY), digestmod=hashlib.sha1) for item in [data['sql'], data['params']]: m.update(force_bytes(item)) return m.hexdigest() @property def connection(self): return connections[self.cleaned_data['alias']] @cached_property def cursor(self): return self.connection.cursor()
class CalculateDepth(forms.Form): latitude = forms.FloatField(min_value=-90.0, max_value=90.0) pressure = forms.FloatField(min_value=0.0, max_value=10000.0)
class OfferAdd(forms.Form): title = forms.CharField() content = forms.CharField() extended_user_id = forms.CharField() inquiry_id = forms.CharField() negotiate_price = forms.FloatField()
class UpdatePrecipRecordForm(forms.Form): precip_type = forms.ModelChoiceField(queryset=Precip_type.objects.all(), required=False) volume_in_inches = forms.FloatField(required=False)
class WithdrawForm(forms.Form): garbage_id = forms.CharField() negotiate_price = forms.FloatField()
class GraphicForm(forms.Form): nbPoints = forms.IntegerField(label="Points",required=False) tMax = forms.FloatField(label="Périodes",required=False)
class DeclineForm(forms.Form): extended_user_id = forms.CharField() inquiry_id = forms.CharField() negotiate_price = forms.FloatField()
class lobForm(forms.Form): Distance = forms.FloatField(min_value=0)
class base_coco(forms.Form): size = forms.FloatField() sh = forms.CharField(widget=forms.Select(choices=Choises))