class TradeForm(Form): amount = DecimalField( 'amount', validators=[Required(), NumberRange(min=Decimal('0.00000001'))]) price = DecimalField( 'price', validators=[Required(), NumberRange(min=Decimal('0.01'))])
class ProfileForm(Form): multipart = True next = HiddenField() email = EmailField(u'Email', [Required(), Email()]) # Don't use the same name as model because we are going to use populate_obj(). avatar_file = FileField(u"Avatar", [Optional()]) sex_code = RadioField(u"Sex", [AnyOf([str(val) for val in SEX_TYPE.keys()])], choices=[(str(val), label) for val, label in SEX_TYPE.items()]) age = IntegerField(u'Age', [Optional(), NumberRange(AGE_MIN, AGE_MAX)]) phone = TelField(u'Phone', [Length(max=64)]) url = URLField(u'URL', [Optional(), URL()]) deposit = DecimalField( u'Deposit', [Optional(), NumberRange(DEPOSIT_MIN, DEPOSIT_MAX)]) location = TextField(u'Location', [Length(max=64)]) bio = TextAreaField(u'Bio', [Length(max=1024)]) submit = SubmitField(u'Save') def validate_name(form, field): user = User.get_by_id(current_user.id) if not user.check_name(field.data): raise ValidationError("Please pick another name.") def validate_avatar_file(form, field): if field.data and not allowed_file(field.data.filename): raise ValidationError("Please upload files with extensions: %s" % "/".join(ALLOWED_AVATAR_EXTENSIONS))
class ParametersForm(Form): oxigen_min = DecimalField(u'Oxígeno Mínimo', [ validators.Required("Campo obligatorio"), validators.NumberRange(0.01, 99.99, "El valor debe estar entre %(min)s y %(max)s"), ]) oxigen_max = DecimalField(u'Oxígeno Máximo', [ validators.Required("Campo obligatorio"), validators.NumberRange(0.01, 99.99, "El valor debe estar entre %(min)s y %(max)s"), ]) cloudiness_max = IntegerField(u'Turbiedad Máxima', [ validators.Required("Campo obligatorio"), validators.NumberRange(1, 9999, "El valor debe estar entre %(min)s y %(max)s"), ])
class APITradeForm(Form): action_type = SelectField('type', validators=[Required()], choices=ACTION_TYPE_CHOICES) amount = DecimalField( 'amount', validators=[Required(), NumberRange(min=Decimal('0.00000001'))]) price = DecimalField( 'price', validators=[Required(), NumberRange(min=Decimal('0.01'))]) def validate_csrf_token(self, field): """ disable csrf protection """ pass
class ProfileForm(Form): next = HiddenField() name = TextField( label = _("Username"), validators = [ Required(), Length(USERNAME_LEN_MIN, USERNAME_LEN_MAX), ], description = u"Combination of letters/digits/underscore, at least %s characters." % USERNAME_LEN_MIN, ) email = EmailField( label = _('Email'), validators = [Email()], ) created_time = DateField( label = _('Created time'), ) role_id = RadioField( label = "Role", validators = [AnyOf([str(val) for val in USER_ROLE.keys()])], choices = [(str(val), label) for val, label in USER_ROLE.items()], ) status_id = RadioField( label = "Status", validators = [AnyOf([str(val) for val in USER_STATUS.keys()])], choices = [(str(val), label) for val, label in USER_STATUS.items()], ) real_name = TextField( label = _('Real name'), validators = [ Length(REALNAME_LEN_MIN, REALNAME_LEN_MAX), ] ) age = IntegerField( label = _('Age'), validators = [NumberRange(AGE_MIN, AGE_MAX)], ) phone = TelField( label = _('Phone'), ) url = URLField( label = _('URL'), validators = [URL()], ) deposit = DecimalField( label = _('Deposit'), validators = [NumberRange(DEPOSIT_MIN, DEPOSIT_MAX)], ) location = TextField( label = _('Location'), validators = [Length(max=50)] ) bio = TextAreaField( label = _('Bio'), validators = [Length(max=1024)] ) submit = SubmitField(_('Save'))
class book_edit_form(Form): title = TextField("Title") imprint = TextField("Imprint") eisbn = TextField("eISBN", validators=[Optional()]) pisbn = TextField("pISBN", validators=[Optional()]) language = TextField("Language") list_price = DecimalField("List Price", places=2, validators=[Optional()]) currency = SelectField( "Currency", choices=[(g, g) for g in ['none', 'USD', 'EUR', 'GBP', 'CAD', 'CNY', 'JPY']]) release_date = DateField("Release Date", validators=[Optional()], format='%m/%d/%Y') publishing_date = DateField("Publishing Date", validators=[Optional()], format='%m/%d/%Y') description = TextAreaField("Description") bisac = TextField("BISAC") bic = TextField("BIC") #TODO: Fix this, this needs to be a list. territory = SelectField("Countries to sell in", choices=[('none', 'none'), ('US', 'US'), ('GB', 'GB'), ('FR', 'FR'), ('IT', 'IT'), ('CN', 'CN'), ('JP', 'JP'), ('ES', 'ES'), ('IE', 'IE'), ('DE', 'DE')], validators=[Optional()]) adult = BooleanField("Is this an adult book?") edition = TextField("Edition") series = SelectField("Series", coerce=int) volume = TextField("Volume") authors = SelectMultipleField("Authors", coerce=int) editors = SelectMultipleField("Editors", coerce=int) illustrators = SelectMultipleField("Illustrators", coerce=int) contributors = SelectMultipleField("Contributors", coerce=int) translators = SelectMultipleField("Translators", coerce=int) def validate_publishing_date(self, field): if field.data > self.release_date.data: raise ValidationError( "The publishing date must be before or equal to the release date." ) def is_isbn_valid(self, isbn): if not isValid(isbn): raise ValidationError("The ISBN entered is not valid.") def validate_eisbn(self, field): self.is_isbn_valid(field.data) def validate_pisbn(self, field): self.is_isbn_valid(field.data)
class TaxRateForm(Form): """Form for existing custom fields already created""" uid = HiddenField(u'ID', [required()]) rate_name = TextField(u'Name', [required()]) rate = DecimalField(u'Value', places=2) def save(self): obj = TaxRate.query.get(self.uid.data) obj.name = self.rate_name.data obj.rate = self.rate.data db.session.add(obj) db.session.commit()
class ProductForm(Form): name = TextField( 'name', validators=[validators.Required(), validators.Length(min=3, max=64)]) price = DecimalField( 'price', validators=[validators.NumberRange(min=0.1, max=100.0)]) slot = IntegerField('slot', validators=[ validators.Required(), validators.NumberRange(min=1, max=5) ]) stock = IntegerField('stock', validators=[validators.Required()]) alert_level = IntegerField('alert_level', validators=[validators.Required()])
class NewTaxRateForm(Form): """Form for a new custom field""" rate_name = TextField(u'Name', validators=[optional()]) rate = DecimalField(u'Value', validators=[optional()], places=2) def save_if_data(self): if self.rate_name.data: if self.rate.data is None: rate = 0.00 else: rate = float(self.rate.data) tax_rate = TaxRate() tax_rate.name = self.rate_name.data tax_rate.rate = rate tax_rate.user_id = current_user.id db.session.add(tax_rate) db.session.commit() return tax_rate else: return None
class ProfileFull(Form): age = DecimalField('age', validators=[Required()]) conditions = SelectField('condition', choices=[("None", "None"), ("Pregnancy", "Pregnancy"), ("Lactation", "Lactation")], validators=[Required()]) weight = DecimalField('weight(lb)', [validators.Optional()]) weightKg = DecimalField('weight(kg)', [validators.Optional()]) heightFeet = DecimalField('height(ft)', [validators.Optional()]) heightInch = DecimalField('height(in)', [validators.Optional()]) heightCm = DecimalField('height(cm)', [validators.Optional()]) activity = SelectField('activity', coerce=float, choices=[(1.2, "Sedentary"), (1.375, "Lightly Active"), (1.55, "Moderately Active"), (1.725, "Very active"), (1.9, "Extremely Active")], validators=[Required()]) submitGuest = SubmitField("Guest") submitSignUp = SubmitField("Sign Up")
class ProfileForm(Form): multipart = True next = HiddenField() email = EmailField(_('Email'), [Required(), Email()]) # Don't use the same name as model because we are going to use populate_obj(). avatar_file = FileField(_("Avatar"), [Optional()]) sex_code = RadioField(_("Sex"), [AnyOf([str(val) for val in SEX_TYPE.keys()])], choices=[(str(val), label) for val, label in SEX_TYPE.items()]) age = IntegerField(_('Age'), [Optional(), NumberRange(AGE_MIN, AGE_MAX)]) phone = TelField(_('Phone'), [Length(max=64)]) url = URLField(_('URL'), [Optional(), URL()]) deposit = DecimalField( _('Deposit'), [Optional(), NumberRange(DEPOSIT_MIN, DEPOSIT_MAX)]) location = TextField(_('Location'), [Length(max=64)]) bio = TextAreaField(_('Bio'), [Length(max=1024)]) submit = SubmitField(_('Save')) def validate_name(form, field): user = User.get_by_id(current_user.id) if not user.check_name(field.data): raise ValidationError(_("Please pick another name.")) def validate_avatar_file(form, field): if field.data and not allowed_file(field.data.filename): raise ValidationError( _("Please upload files with extensions:") + " %s" % "/".join(ALLOWED_AVATAR_EXTENSIONS)) def create_profile(self, request, user): if self.avatar_file.data: upload_file = request.files[self.avatar_file.name] if upload_file and allowed_file(upload_file.filename): # Don't trust any input, we use a random string as filename. # or use secure_filename: # http://flask.pocoo.org/docs/patterns/fileuploads/ user_upload_dir = os.path.join( current_app.config['UPLOAD_FOLDER'], "user_%s" % user.id) current_app.logger.debug(user_upload_dir) make_dir(user_upload_dir) root, ext = os.path.splitext(upload_file.filename) today = datetime.now().strftime('_%Y-%m-%d') # Hash file content as filename. hash_filename = hashlib.sha1( upload_file.read()).hexdigest() + "_" + today + ext user.avatar = hash_filename avatar_ab_path = os.path.join(user_upload_dir, user.avatar) # Reset file curso since we used read() upload_file.seek(0) upload_file.save(avatar_ab_path) self.populate_obj(user) self.populate_obj(user.user_detail) db.session.add(user) db.session.commit()
class InvoiceItemForm(Form): invoice_id = IntegerField(u'Invoice id', validators=[required()]) type_id = SelectField(u'Type', coerce=int, validators=[required()]) tax_rate_id = SelectField(u'Tax rate', coerce=int) description = TextField(u'Description', validators=[required()]) quantity = DecimalField(u'Quantity') price = DecimalField(u'Price', default=0) def __init__(self, formdata=None, obj=None, prefix='', **kwargs): super(InvoiceItemForm, self).__init__(formdata, obj, prefix, **kwargs) self.type_id.choices = self.get_type_options() self.tax_rate_id.choices = self.get_tax_rate_options() if obj: self.model = obj else: self.model = None self.price.default = 0 self.price.process(formdata) def validate_quantity(form, field): """Comments don't require a price, everything else does""" item_type = InvoiceItemType.query.get(form.type_id.data) if item_type.name == 'Comment': field.data = 0 else: if field.data == None: raise ValidationError('Quantity must be supplied') def validate_price(form, field): """Comments don't require a price, everything else does""" item_type = InvoiceItemType.query.get(form.type_id.data) if item_type.name == 'Comment': field.data = 0 else: if field.data == None: raise ValidationError('Price must be supplied') def get_type_options(self): """Get item types""" options = [] types = InvoiceItemType.query.order_by('sort_order asc').all() for t in types: options.append((t.id, t.name)) return options def get_tax_rate_options(self): """Get all tax rates""" options = [] tax_rates = TaxRate.query.filter_by(user_id=current_user.id).all() for rate in tax_rates: options.append((rate.id, rate.name)) options.append((-1, 'None')) return options def save(self): """Save new invoice item""" invoice = Invoice.query.get(self.invoice_id.data) if not self.model: item = InvoiceItem() else: item = self.model item.invoice_id = self.invoice_id.data item.type_id = self.type_id.data if (self.tax_rate_id.data != -1): item.tax_rate_id = self.tax_rate_id.data item.description = self.description.data item.quantity = float(self.quantity.data) item.price = float(self.price.data) item.sort_order = invoice.next_item_sort_order() item.update_totals() db.session.add(item) db.session.commit() return item