Esempio n. 1
0
class RestaurantForm(FlaskForm):
    name = f.StringField('Name', validators=[DataRequired()])
    lat = f.FloatField('Latitude', validators=[DataRequired()])
    lon = f.FloatField('Longitude', validators=[DataRequired()])
    phone = f.StringField('Phone', validators=[DataRequired()])

    # Note: the capacity is automatically derived from tables settings

    cuisine_type = f.SelectMultipleField(
        'Cuisine types', 
        choices = Restaurant.CUISINE_TYPES.choices(),
        coerce = Restaurant.CUISINE_TYPES.coerce, 
        validators=[DataRequired()]
    )
    prec_measures = f.TextAreaField('Precautionary measures',validators=[DataRequired()])
    avg_time_of_stay = f.IntegerField('Average time of stay (in minutes)', validators=[DataRequired(), NumberRange(min=15)])

    workingdays = f.FieldList(f.FormField(WorkingDayForm), min_entries=1, max_entries=7)
    tables = f.FieldList(f.FormField(TableForm), min_entries=1, max_entries=100)
    dishes = f.FieldList(f.FormField(DishForm), min_entries=1, max_entries=100)

    display = ['name', 'lat', 'lon', 'phone', 'cuisine_type', 'prec_measures', 'avg_time_of_stay']
    
    def validate_workingdays(form, field):
        days_already_added = []
        for wd in field.data:
            if wd['day'] in days_already_added:
                raise ValidationError("There cannot be two working days with the same day")
            else:
                days_already_added.append(wd['day'])
Esempio n. 2
0
class CreateModuleForm(wtf.Form):
    name = wtforms.StringField("Name")
    version = wtforms.StringField("Version")
    release = wtforms.StringField("Release")
    filter = wtforms.FieldList(wtforms.StringField("Package Filter"))
    api = wtforms.FieldList(wtforms.StringField("Module API"))
    profile_names = wtforms.FieldList(wtforms.StringField("Install Profiles"),
                                      min_entries=2)
    profile_pkgs = wtforms.FieldList(wtforms.FieldList(
        wtforms.StringField("Install Profiles")),
                                     min_entries=2)

    def validate(self):
        if not wtf.Form.validate(self):
            return False

        # Profile names should be unique
        names = filter(None, self.profile_names.data)
        if len(set(names)) < len(names):
            self.errors["profiles"] = ["Profile names must be unique"]
            return False

        # WORKAROUND
        # profile_pkgs are somehow sorted so if I fill profile_name in the first box and
        # profile_pkgs in seconds box, it is sorted and validated correctly
        for i in range(0, len(self.profile_names.data)):
            # If profile name is not set, then there should not be any packages in this profile
            if not flask.request.form["profile_names-{}".format(i)]:
                if [
                        j for j in range(0, len(self.profile_names)) if
                        "profile_pkgs-{}-{}".format(i, j) in flask.request.form
                ]:
                    self.errors["profiles"] = ["Missing profile name"]
                    return False
        return True
Esempio n. 3
0
class RecipeEdit(Form):
    START_NUM_INGREDIENTS = RECIPE_START_NUM_INGREDIENTS
    MIN_INGREDIENTS = RECIPE_MIN_INGREDIENTS
    MIN_GROUPS = RECIPE_MIN_GROUPS

    title = wtf.TextField("Title")
    description = wtf.TextAreaField("Description")
    instructions = wtf.TextAreaField("Instructions")
    photo = wtf.FileField("Photo", validators=[valid_photo])
    tags = TagListField("Tags", validators=[valid_tags])
    general_ingredients = wtf.FieldList(wtf.FormField(IngredientForm),
                                        min_entries=RECIPE_MIN_INGREDIENTS,
                                        max_entries=RECIPE_MAX_INGREDIENTS)
    ingredient_groups = wtf.FieldList(wtf.FormField(IngredientGroup),
                                      min_entries=RECIPE_MIN_GROUPS,
                                      max_entries=RECIPE_MAX_GROUPS)

    @classmethod
    def from_recipe(cls, recipe, *args, **orig_kwargs):
        kwargs = dict(orig_kwargs)
        kwargs['title'] = recipe.title
        kwargs['description'] = recipe.description
        kwargs['instructions'] = recipe.instructions
        kwargs['general_ingredients'] = [
            IngredientForm.from_model(i) for i in recipe.general_ingredients
        ]
        kwargs['ingredient_groups'] = [
            IngredientGroup.from_model(g) for g in recipe.ingredient_groups
        ]
        kwargs['tags'] = recipe.tags
        return cls(*args, **kwargs)

    def save_recipe(self, recipe):
        """
        Update a recipe from the form data
        """

        if self.photo.data:
            recipe.photo = photos.save(self.photo.data.stream)

        recipe.title = self.title.data
        recipe.title_slug = slugify(self.title.data)
        recipe.description = self.description.data
        recipe.instructions = self.instructions.data
        recipe.general_ingredients = [
            i.to_model() for i in self.general_ingredients
        ]
        recipe.ingredient_groups = [
            g.to_model() for g in self.ingredient_groups
        ]
        recipe.tags = self.tags.data

        recipe.save()
Esempio n. 4
0
class NotifyForm(wtforms.Form):
    is_tested = wtforms.BooleanField('Is tested against COVID-19', default=False)
    comment = wtforms.StringField('Comment', [wtforms.validators.Length(max=1000)])

    keys = wtforms.FieldList(wtforms.FormField(DailyKeyForm))

    def validate_keys(form, field):
        if not field.data:
            return

        expected_keys_count = INCUBATION_PERIOD + SYMPTOMS_TO_VIRUS_NEGATIVE

        key_values = set(key['value'] for key in field.data)

        # All keys should be unique, and should match the expected count
        if len(key_values) != expected_keys_count:
            raise wtforms.ValidationError(
                'Should contain {} daily keys.'.format(expected_keys_count)
            )

        key_dates = sorted(key['date'] for key in field.data)

        # There should not be any missing date
        prev_date = None
        for date in key_dates:
            if prev_date is not None and date != prev_date + datetime.timedelta(days=1):
                raise wtforms.ValidationError('Key dates should not contain gaps.')

            prev_date = date

        if key_dates[0] > datetime.datetime.utcnow().date():
            raise wtforms.ValidationError('Key dates can not all be in the future.')
Esempio n. 5
0
class GameForm(wtforms.Form):
    """A form for entering info to start a game."""

    num_players = wtforms.IntegerField("How many players?")
    set_num_players = wtforms.SubmitField("Go")

    roles = wtforms.FieldList(
        wtforms.SelectField(choices=role_choices, coerce=int, default=3))

    start_phase = wtforms.SelectField("Start phase",
                                      choices=[(0, "Day"), (1, "Night")],
                                      coerce=int,
                                      default=0)
    submit = wtforms.SubmitField("Start Game")

    def validate_num_players(form, field):
        """Make sure num_players contains an integer that is at least 3.
        wtforms.validators.NumberRange isn't good enough because it raises
        an error if num_players contains an invalid integer."""

        # field.data is None if a proper integer wasn't passed in
        if field.data is not None and field.data < 3:
            raise wtforms.validators.ValidationError(
                "Mafia isn't fun with fewer than 3 players")

    def add_role_fields(self, n):
        """Add or remove role fields from this form so that there are
        fields for exactly n roles."""

        num_players = len(self.roles)
        append_or_pop = (self.roles.append_entry
                         if num_players < n else self.roles.pop_entry)

        for i in range(abs(n - num_players)):
            append_or_pop()
Esempio n. 6
0
def attachment_form_group_create(schema_prop):
    """Creates a wtforms.FieldList for attachments."""

    file_select_form_group = _attachment_build_single_field(schema_prop)
    field = wtforms.FieldList(CustomFormField(file_select_form_group), min_entries=1)

    return field
Esempio n. 7
0
class InstrumentList(wtf.Form):
    '''
    '''
    curve_date = wtffields.DateField('Curve date')
    curve_type = wtf.SelectField('Curve type', choices=conv.CURVE_TYPES)
    currency = wtf.TextField('Currency')
    instruments = wtf.FieldList(wtf.FormField(Instrument), min_entries=3)
    submit = wtf.SubmitField()
Esempio n. 8
0
 class PatientForm(Form):
     site = ModelField(
         dbsession=dbsession,
         class_=models.Site,
         validators=[
             wtforms.validators.InputRequired(),
             check_allowed])
     references = wtforms.FieldList(wtforms.FormField(ReferenceForm))
Esempio n. 9
0
class TestForm(TornadoForm):
    msg = wtforms.StringField('msg', [validators.Length(min=4, max=23)])
    lst = wtforms.FieldList(wtforms.StringField('lst'))  # 数组
    dit = wtforms.FormField(TelephoneForm)  # 字典判断

    def validate_msg(self, field):
        # 自定义验证器
        if field.data != 'hello world':
            raise ValidationError(u'Must be hello world')
Esempio n. 10
0
 class VisitForm(Form):
     cycles = wtforms.FieldList(ModelField(
         db_session=db_session,
         class_=models.Cycle,
         validators=[wtforms.validators.InputRequired(), unique_cycle]),
                                min_entries=1)
     visit_date = DateField(validators=[
         wtforms.validators.InputRequired(),
         DateRange(min=date(1900, 1, 1)), unique_visit_date
     ])
     include_forms = wtforms.BooleanField()
     include_specimen = wtforms.BooleanField()
Esempio n. 11
0
 class SchemaManagementForm(Form):
     schema = wtforms.StringField(validators=[
         wtforms.validators.InputRequired(), check_not_patient_schema,
         check_not_randomization_schema, check_not_termination_schema
     ])
     versions = wtforms.FieldList(
         ModelField(db_session=db_session,
                    class_=datastore.Schema,
                    validators=[
                        wtforms.validators.InputRequired(), check_published
                    ]),
         validators=[wtforms.validators.DataRequired(), check_same_schema])
Esempio n. 12
0
class PostForm(FlaskForm):
    user_ids = form.FieldList(form.IntegerField(),
                              validators=[v.DataRequired()])
    message = form.StringField(validators=[v.InputRequired()])
    img_url = form.StringField(validators=[v.Optional(), v.URL()])
    expire = form.IntegerField(validators=[v.optional(), v.NumberRange(min=0)])
    lesson_id = form.IntegerField(validators=[v.Optional()])
    show_at = form.DateTimeField(validators=[v.Optional(),
                                             Future()],
                                 format='%d.%m.%Y %H:%M')

    class Meta:
        csrf = False
Esempio n. 13
0
class UploadsForm(wtforms.Form):
    enctype = ' enctype="multipart/form-data"'
    uploads = wtforms.FieldList(wtforms.FormField(UploadForm))

    def __init__(self, images=None, *args, **kwargs):
        super(UploadsForm, self).__init__(*args, **kwargs)

        if not kwargs.get('formdata'):
            for image in images or []:
                self.uploads.append_entry({'filename': image})

        for filename, field in zip(images, self.uploads):
            field.label = filename
            field.file.label = ''
Esempio n. 14
0
class ResourceUpdateForm(flask_wtf.FlaskForm):
    name = wtforms.TextField(u'عنوان الصورة', [wtforms.validators.required()])
    description = wtforms.TextAreaField(u'وصف الصورة',
                                        [wtforms.validators.optional()])
    address_first_line = wtforms.TextField(u'عنوان الشارع',
                                           [wtforms.validators.optional()])
    address_second_line = wtforms.TextField(u'القرية/الحارة/المنطقة',
                                            [wtforms.validators.optional()])
    city = wtforms.TextField(u'المدينة', [wtforms.validators.optional()])
    country = wtforms.TextField(u'البلد', [wtforms.validators.optional()])
    tags = wtforms.FieldList(wtforms.TextField(u'كلمة وصفية'),
                             min_entries=2,
                             label=u'الكلمات الوصفية الحالية')
    new_tags = wtforms.TextField(u'كلمات وصفية جديدة (افصل بينهم بفاصلة)')
Esempio n. 15
0
 class FieldForm(Form):
     name = wtforms.StringField(
         validators=[
             wtforms.validators.InputRequired(),
             wtforms.validators.Length(min=2, max=100),
             wtforms.validators.Regexp(
                 RE_VALID_NAME,
                 message=_(u'Not a valid variable name')),
             wtforms.validators.NoneOf(
                 RESERVED_WORDS,
                 message=_(u'Can\'t use reserved programming word')),
             unique_variable])
     title = wtforms.StringField(validators=[
         wtforms.validators.Optional()])
     description = wtforms.StringField(
         widget=wtforms.widgets.TextInput(),
         validators=[wtforms.validators.Optional()])
     type = wtforms.StringField(
         validators=[
             wtforms.validators.InputRequired(),
             wtforms.validators.AnyOf(set(t['name'] for t in types))])
     is_required = wtforms.BooleanField(
         validators=[wtforms.validators.Optional()])
     is_private = wtforms.BooleanField(
         validators=[wtforms.validators.Optional()])
     is_system = wtforms.BooleanField(
         validators=[wtforms.validators.Optional()])
     is_readonly = wtforms.BooleanField(
         validators=[wtforms.validators.Optional()])
     # Choice
     is_collection = wtforms.BooleanField(
         validators=[wtforms.validators.Optional()])
     # Choice
     is_shuffled = wtforms.BooleanField(
         validators=[wtforms.validators.Optional()])
     # Numbers
     decimal_places = wtforms.IntegerField(
         validators=[wtforms.validators.Optional()])
     # Number/String/Multichoice
     value_min = wtforms.IntegerField(
         validators=[wtforms.validators.Optional()])
     # Number/String/Multichoice
     value_max = wtforms.IntegerField(
         validators=[wtforms.validators.Optional()])
     # String
     pattern = wtforms.StringField(
         validators=[wtforms.validators.Optional()])
     choices = wtforms.FieldList(wtforms.FormField(ChoiceForm))
Esempio n. 16
0
class IngredientGroup(Form):
    title = wtf.TextField("Ingredient group name",
                          validators=[
                              wtf.validators.Required(
                                  message="Ingredient group name is required")
                          ])
    ingredients = wtf.FieldList(wtf.FormField(IngredientForm),
                                min_entries=RECIPE_MIN_INGREDIENTS,
                                max_entries=RECIPE_MAX_INGREDIENTS)

    def __init__(self, *args, **kwargs):
        kwargs['csrf_enabled'] = False
        super(IngredientGroup, self).__init__(*args, **kwargs)

    @staticmethod
    def from_model(ingredient_group):
        """
        Convert ingredient group model to dictionary of
        values used for filling out form data
        """

        return {
            'title':
            ingredient_group.title,
            'ingredients': [
                IngredientForm.from_model(i)
                for i in ingredient_group.ingredients
            ],
        }

    def to_model(self):
        """
        Convert an ingredient group from the form data
        to an ingredient group model
        """

        ingredient_group = models.IngredientGroup()
        ingredient_group.title = self.title.data
        ingredient_group.ingredients = [i.to_model() for i in self.ingredients]
        return ingredient_group
Esempio n. 17
0
class BattleEditForm(asb.forms.CSRFTokenForm):
    """An admin-only form for editing a battle."""

    title = wtforms.TextField('Title')
    refs = wtforms.FieldList(
        wtforms.FormField(BattleEditRefForm, [wtforms.validators.Optional()]),
    )
    save = wtforms.SubmitField('Save')

    def set_refs(self, battle):
        """Set data for the ref table based on the battle's current refs."""

        for ref in battle.all_refs:
            print(self.refs.data)
            self.refs.append_entry({
                'ref': ref.trainer.name,
                'current': ref.is_current_ref,
                'emergency': ref.is_emergency_ref
            })

        # Also add one blank row
        self.refs.append_entry()
Esempio n. 18
0
def make_relation_field(model, *args, **kwargs):
    class ItemWidget(unicode):
        def all_objects(self):
            return model.query.all()

        def object_title(self, obj):
            object_title_attr = kwargs.get('object_title_attr')
            if object_title_attr:
                return getattr(obj, object_title_attr)
            else:
                return getattr(obj, 'title', unicode(obj))

    class RelationField(wtforms.IntegerField):
        widget = wtforms.widgets.HiddenInput()

        def process_formdata(self, valuelist):
            [id] = valuelist
            self.data = model.query.get(id)

    return wtforms.FieldList(
        RelationField(),
        *args,
        widget=ItemWidget('sapyens.crud:templates/relation.mako'))
Esempio n. 19
0
class CreateModuleForm(FlaskForm):
    builds = wtforms.FieldList(wtforms.StringField("Builds ID list"))
    packages = wtforms.FieldList(wtforms.StringField("Packages list"))
    filter = wtforms.FieldList(wtforms.StringField("Package Filter"))
    api = wtforms.FieldList(wtforms.StringField("Module API"))
    profile_names = wtforms.FieldList(wtforms.StringField("Install Profiles"),
                                      min_entries=2)
    profile_pkgs = wtforms.FieldList(wtforms.FieldList(
        wtforms.StringField("Install Profiles")),
                                     min_entries=2)

    def __init__(self, copr=None, *args, **kwargs):
        self.copr = copr
        super(CreateModuleForm, self).__init__(*args, **kwargs)

    def validate(self):
        if not FlaskForm.validate(self):
            return False

        # Profile names should be unique
        names = [x for x in self.profile_names.data if x]
        if len(set(names)) < len(names):
            self.errors["profiles"] = ["Profile names must be unique"]
            return False

        # WORKAROUND
        # profile_pkgs are somehow sorted so if I fill profile_name in the first box and
        # profile_pkgs in seconds box, it is sorted and validated correctly
        for i in range(0, len(self.profile_names.data)):
            # If profile name is not set, then there should not be any packages in this profile
            if not flask.request.form["profile_names-{}".format(i)]:
                if [
                        j for j in range(0, len(self.profile_names)) if
                        "profile_pkgs-{}-{}".format(i, j) in flask.request.form
                ]:
                    self.errors["profiles"] = ["Missing profile name"]
                    return False
        return True
Esempio n. 20
0
 class AliquotCrudForm(wtforms.Form):
     aliquot = wtforms.FieldList(wtforms.FormField(AliquotForm))
Esempio n. 21
0
 class SpecimenCrudForm(wtforms.Form):
     specimen = wtforms.FieldList(wtforms.FormField(SpecimenAliquotForm))
Esempio n. 22
0
class LinksListForm(Form):
    links = wtforms.FieldList(wtforms.FormField(LinkForm), max_entries=5)
Esempio n. 23
0
class Transfer(FlaskForm):
    private_key = wtf.StringField('Private Key')
    recipients = wtf.FieldList(wtf.FormField(Recipient), min_entries=1)
    submit = wtf.SubmitField('Send')
Esempio n. 24
0
class ModelForm(Form):

    def __init__(self, csrf_enabled=False, *args, **kwargs):
        super(ModelForm, self).__init__(csrf_enabled=csrf_enabled, *args, **kwargs)

    ### Methods

    def required_if_method(value):
        def _required(form, field):
            if form.method.data == value:
                if not field.data or (isinstance(field.data, str) and field.data.strip() == ""):
                    raise validators.ValidationError('This field is required.')
            else:
                field.errors[:] = []
                raise validators.StopValidation()
        return _required

    def validate_NetParameter(form, field):
        pb = caffe_pb2.NetParameter()
        try:
            text_format.Merge(field.data, pb)
        except text_format.ParseError as e:
            raise validators.ValidationError('Not a valid NetParameter: %s' % e)

    ### Fields

    # The options for this get set in the view (since they are dynamic)
    dataset = wtforms.SelectField('Select Dataset', choices=[])

    train_epochs = wtforms.IntegerField('Training epochs',
            validators = [
                validators.NumberRange(min=1)
                ],
            default=30,
            )

    val_interval = wtforms.IntegerField('Validation interval (in epochs)',
            validators = [
                validators.NumberRange(min=0)
                ],
            default=1,
            )

    batch_size = wtforms.IntegerField('Batch size',
            validators = [
                validators.NumberRange(min=1),
                validators.Optional(),
                ],
            )

    ### Learning rate

    learning_rate = wtforms.FloatField('Base Learning Rate',
            default = 0.01,
            validators = [
                validators.DataRequired(),
                validators.NumberRange(min=0),
                ]
            )

    lr_policy = wtforms.SelectField('Policy',
            choices = [
                ('fixed', 'Fixed'),
                ('step', 'Step Down'),
                ('multistep', 'Step Down (arbitrary steps)'),
                ('exp', 'Exponential Decay'),
                ('inv', 'Inverse Decay'),
                ('poly', 'Polynomial Decay'),
                ('sigmoid', 'Sigmoid Decay'),
                ],
            default = 'step'
            )

    lr_step_size = wtforms.FloatField('Step Size',
            default = 33
            )
    lr_step_gamma = wtforms.FloatField('Gamma',
            default = 0.1
            )
    lr_multistep_values = wtforms.StringField('Step Values',
            default = "50,85"
            )
    def validate_lr_multistep_values(form, field):
        if form.lr_policy.data == 'multistep':
            for value in field.data.split(','):
                try:
                    v = float(value)
                except ValueError:
                    raise validators.ValidationError('invalid value')
    lr_multistep_gamma = wtforms.FloatField('Gamma',
            default = 0.5
            )
    lr_exp_gamma = wtforms.FloatField('Gamma',
            default = 0.95
            )
    lr_inv_gamma = wtforms.FloatField('Gamma',
            default = 0.1
            )
    lr_inv_power = wtforms.FloatField('Power',
            default = 0.5
            )
    lr_poly_power = wtforms.FloatField('Power',
            default = 3
            )
    lr_sigmoid_step = wtforms.FloatField('Step',
            default = 50
            )
    lr_sigmoid_gamma = wtforms.FloatField('Gamma',
            default = 0.1
            )

    ### Network

    method = wtforms.HiddenField('Model type',
            validators = [
                validators.AnyOf(
                    ['standard', 'previous', 'custom'],
                    message='The method you chose is not currently supported.'
                    )
                ],
            default = 'standard',
            )

    # The options for this get set in the view (since they are dependent on )
    standard_networks = wtforms.RadioField('Standard Networks',
            validators = [
                required_if_method('standard'),
                ],
            )

    previous_networks = wtforms.RadioField('Previous Networks',
            choices = [],
            validators = [
                required_if_method('previous'),
                ],
            )

    previous_network_snapshots = wtforms.FieldList(
            wtforms.SelectField('Snapshots',
                validators = [validators.Optional()]
                ),
            )

    custom_network = wtforms.TextAreaField('Custom Network',
            validators = [
                required_if_method('custom'),
                validate_NetParameter,
                ]
            )

    custom_network_snapshot = wtforms.TextField('Pretrained model')

    def validate_custom_network_snapshot(form, field):
        if form.method.data == 'custom':
            snapshot = field.data.strip()
            if snapshot:
                if not os.path.exists(snapshot):
                    raise validators.ValidationError('File does not exist')

    model_name = wtforms.StringField('Model Name',
            validators = [
                validators.DataRequired()
                ]
            )
Esempio n. 25
0
class EditMetaDataForm(wtforms.Form):
    media_metadata = wtforms.FieldList(wtforms.FormField(MetaDataForm, ""), )
Esempio n. 26
0
class TargetForm(wtforms.Form):
    """A form for a player to choose night action targets."""

    targets = wtforms.FieldList(wtforms.SelectField(choices=[], coerce=int))
    submit = wtforms.SubmitField("Submit")
Esempio n. 27
0
 class CrudForm(wtforms.Form):
     aliquot = wtforms.FieldList(wtforms.FormField(CheckoutForm))
Esempio n. 28
0
class EpisodesImportForm(wtforms.Form):
    """ This is used for adding episodes to the database """
    media = wtforms.FieldList(wtforms.FormField(EpisodeForm))
Esempio n. 29
0
class EpisodesSeasonForm(wtforms.Form):
    """ This is used for adding episodes to seasons """
    media = wtforms.FieldList(wtforms.FormField(SeasonEpisodeForm))
Esempio n. 30
0
class EncounterStartForm(w.Form):
  actors = f.FieldList(f.FormField(EncounterActorStartForm,""),"")
  events = f.FieldList(f.FormField(EncounterEventStartForm,""),"")

  start = f.SubmitField('Start encounter')