示例#1
0
class SearchForm(Form):
    date = DateField(u'Enter Date', format='%Y-%m-%d')
    destination = SelectField(u'Select destination to search for',
                              choices=[('Allahabad Station',
                                        'Allahabad Station'),
                                       ('PVR Vinayak', 'PVR Vinayak'),
                                       ('Civil Lines', 'Civil Lines'),
                                       ('Prayag Station', 'Prayag Station')])
    trainno = IntegerField(u'Enter Train no', [
        validators.NumberRange(max=99999, message='Not a Valid Train No.'),
        validators.optional()
    ],
                           default=None)
示例#2
0
class SearchForm(FlaskForm):
    week_ago = datetime.today() - timedelta(days=7)

    start_date = DateField(label="Start Date",
                           default=week_ago,
                           validators=[Required])
    end_date = DateField(label="End Date",
                         default=datetime.today,
                         validators=[Required])
    user_name = StringField("User Name/Email Address")
    last_name = StringField("Last Name")
    org = SelectField("Organization", coerce=int)
    submit = SubmitField('Submit')
    csrf_token = HiddenField(default=os.environ.get("SECRET_KEY"))
示例#3
0
class EventForm(FlaskForm):
    guest_name = StringField('Your name', validators=[DataRequired()])
    """Guest Name"""
    event_name = StringField('Title of Appointment (optional)')
    """Name of event (optional)"""
    event_description = StringField('Description')
    """Event's description"""

    event_date = IntegerField('Date of event')
    """Event's date"""
    event_month = IntegerField('Month of event')
    """Event's date"""
    event_year = IntegerField('Year of event')
    """Event's date"""

    timeRange = initTimeRange()
    "List of tuple of time such as [(0,'9:0AM'), (15,'9:15AM'), (30,'9:30AM'),... (240,'1:0PM'),...]"
    start_time = SelectField('Start time', choices=timeRange)
    """Start of working hour"""
    end_time = SelectField('End time', choices=timeRange)
    """End of working hour"""

    submit = SubmitField('Make Appointment')
    """Sign-in button"""
示例#4
0
class BackgroundImageForm(BaseForm):
    file = FileField(u"Background FITS Image",
                     validators=[FileAllowed(['fits'], "FITS Files Only")])
    orig_filename = HiddenField()
    current_filename = HiddenField()
    file_path = HiddenField()
    in_imgs_id = HiddenField(default='')
    units = SelectField(u"Image Units", default=u"s", choices=unit_choices)
    scale = FloatField(u"Pixel Scale", default=0.1)
    wcs = BooleanField(u"Take WCS from File", default=False)
    poisson = BooleanField(u"Add Poisson Noise", default=True)
    ext = IntegerField(u"Image Extension", default=1)
    sim_prefix = HiddenField()
    field_order = ('file', 'orig_filename', 'current_filename', 'units',
                   'scale', 'wcs', 'poisson', 'ext', 'in_imgs_id',
                   'sim_prefix')
示例#5
0
class ObservationForm(Form):
    instrument = HiddenField()
    detectors = NonValidatingSelectField("Detectors to Include")
    default = BooleanField(u"Include Centred Exposure", default=True)
    exptime = FloatField(
        u"Exposure Time",
        default=1000.0,
        validators=[validators.NumberRange(min=1., max=10000.)])
    filters = MultiCheckboxField(u"Filters")
    oversample = IntegerField(
        u"Oversample Image By",
        default=1,
        validators=[validators.NumberRange(min=1, max=20)])
    pupil_mask = TextField(u"PSF Pupil Mask",
                           default="",
                           validators=[validators.Optional()])
    background = SelectField(u"Background")
    distortion = BooleanField(u"Include Image Distortion", default=False)
    observations_id = HiddenField(default='')
    sim_prefix = HiddenField()

    def __init__(self, *args, **kwargs):
        super(ObservationForm, self).__init__(*args, **kwargs)

        instruments = DefaultSettings.instruments

        self.filters.choices = [
            (x, x) for x in instruments[self.instrument.data].FILTERS
        ]
        self.background.choices = [
            (x, y)
            for x, y in zip(instruments[self.instrument.data].BACKGROUNDS_V,
                            instruments[self.instrument.data].BACKGROUNDS)
        ]
        self.background.default = self.background.choices[0][0]
        self.detectors.choices = [
            (x, x) for x in instruments[self.instrument.data].N_DETECTORS
        ]

    def validate_detectors(self, field):
        if field.data not in [
                str(x) for x in DefaultSettings.instruments[
                    self.instrument.data].N_DETECTORS
        ]:
            raise ValidationError("Detectors must be one of {}".format(
                instruments[self.instrument.data].N_DETECTORS))
def buildDeparturesFieldPlane(departure):
	departures = getListOfDeparturesPlane()
	members = []
	departNames = []	
	default_selection = 0
	
		
	i = 0

	members.append(None)
	departNames.append('--')
	i=i+1		
	
	for row in departures:
		#print(str(row[1]))
	
		#if(str(row[1]) != 'None' and i > 0):
		if(i > 0):
			members.append(i)
			departNames.append(str(row[1]))
			print("departure="+departure+"depart from mysql="+str(row[1]))
			i=i+1
		
	#departNames = set(departNames) # this changed the order after removing duplicates
	departNames = sorted(set(departNames), key=departNames.index)
	zip(members,departNames)
	departs = [(value, value) for value in departNames]
	
	d = 0
	for name in departNames:
		if(name == departure):
			default_selection = d
		d = d+1
		
	if default_selection != 0:
		defaultSelection = departNames[default_selection]
	else:
		defaultSelection = 0
	
	return SelectField(choices=departs, default = defaultSelection,id="departLocation")
def buildArrivalsFieldPlane(departure,arrival):

	arrivals = getListOfArrivalsFromDeparturePlane(departure)
	members = []
	arriveNames = []	
	default_selection = 0
	
		
	i = 0

	members.append(None)
	arriveNames.append('--')
	i=i+1		
	
	for row in arrivals:
		#print(str(row[1]))
	
		#if(str(row[1]) != 'None' and i > 0):
		if(i > 0):
			members.append(i)
			arriveNames.append(str(row[3]))
			i=i+1
		
	arriveNames = sorted(set(arriveNames), key=arriveNames.index)
	zip(members,arriveNames)
	arrivals = [(value, value) for value in arriveNames]
	
	d = 0
	for name in arriveNames:
		if(name == arrival):
			default_selection = d
		d = d+1
		
	if default_selection != 0:
		defaultSelection = arriveNames[default_selection]
	else:
		defaultSelection = 0
	
	return SelectField(choices=arrivals, default = defaultSelection,id="arriveLocation")
示例#8
0
class EnergySearchForm(FlaskForm):
    """Form for appliance energy calculator"""

    appliance = SelectField('My appliance', coerce=int)
    watts = IntegerField('Wattage', validators=[InputRequired()])
    rate = FloatField('Utility Rate, ¢/kWh', validators=[InputRequired()])
    hours = IntegerField('Hours used per day',
                         validators=[
                             NumberRange(
                                 min=1,
                                 max=24,
                                 message="Please enter 24 hours or less"),
                             InputRequired()
                         ])
    days = IntegerField('Days used per year',
                        validators=[
                            NumberRange(min=1,
                                        max=365,
                                        message="Please enter 365 or less"),
                            InputRequired()
                        ])
    zipcode = StringField('Zip or Postal Code', validators=[InputRequired()])
示例#9
0
def populate_select_meal_form(meal_data):
    """Delete old fields and add new fields to the select meal form for each meal"""
    for field in SelectMealForm()._fields:
        if field != 'csrf_token':
            delattr(SelectMealForm, field)

    fields = {}

    for n in range(meal_data["Breakfast"]):
        fields[f"breakfast{n}"] = "Breakfast"

    for n in range(meal_data["Lunch"]):
        fields[f"lunch{n}"] = "Lunch"

    for n in range(meal_data["Dinner"]):
        fields[f"dinner{n}"] = "Dinner"

    for key, value in fields.items():
        if meal_data[value] > 0:
            setattr(SelectMealForm, key, SelectField(value, coerce=int))

    return fields
示例#10
0
def buildDeparturesFieldTrain(departure):
    departures = getListOfDeparturesTrain()
    members = []
    departNames = []
    default_selection = 0
    i = 0
    members.append(None)
    departNames.append('--')
    i = i + 1

    for row in departures:

        if (i > 0):
            members.append(i)
            departNames.append(str(row[1]))
            print("departure=" + departure + "depart from mysql=" +
                  str(row[1]))
            i = i + 1

    departNames = sorted(set(departNames), key=departNames.index)
    zip(members, departNames)
    departs = [(value, value) for value in departNames]

    d = 0
    for name in departNames:
        if (name == departure):
            default_selection = d
        d = d + 1

    if default_selection != 0:
        defaultSelection = departNames[default_selection]
    else:
        defaultSelection = 0

    return SelectField(choices=departs,
                       default=defaultSelection,
                       id="departLocation")
示例#11
0
def buildDepartTimesFieldPlane(departure,arrival,time):
	times = getListOfDepartureTimesPlane(departure,arrival)
	members = []
	departTimes = []
	default_selection = 0
	
	i = 0

	members.append(None)
	departTimes.append('--')
	i=i+1	
			
	for row in times:
		#print(str(row[1]))
		if(str(row[2]) != 'None'):
			members.append(i)
			departTimes.append(str(row[2]))
			i=i+1

			
	departTimes = sorted(set(departTimes), key=departTimes.index)
	zip(members,departTimes)
	times = [(value, value) for value in departTimes]
	
	d = 0
	for t in departTimes:
		if(time == t):
			default_selection = d
		d=d+1
	
	if(time != 0):
			defaultSelection = departTimes[default_selection] 
	else:
		defaultSelection = 0
	
	return SelectField(choices=times,default=defaultSelection,id="departTime")
示例#12
0
class FormAdmin(PageAdmin):
    column_extra_row_actions = [
        EndpointLinkRowAction(
            icon_class="fa fa-download",
            endpoint=".export_entries",
            title=lazy_gettext("Export Entries as CSV"),
            id_arg="pk",
        ),
        EndpointLinkRowAction(
            icon_class="fa fa-table",
            endpoint=".view_entries",
            title=lazy_gettext("View Entries"),
            id_arg="pk",
        ),
    ]
    form_excluded_columns = list(PageAdmin.form_excluded_columns) + [
        "author",
        "created",
        "updated",
        "entries",
    ]
    form_columns = list(PageAdmin.form_columns)
    form_columns.insert(6, "fields")
    form_columns.insert(7, "submit_text")
    form_columns.insert(8, "submit_message")
    form_overrides = {"submit_message": CkeditorTextAreaField}
    inline_models = [
        (
            Field,
            dict(
                form_columns=[
                    "id",
                    "name",
                    "label",
                    "description",
                    "type",
                    "choices",
                    "default",
                    "required",
                    "max_length",
                ],
                form_extra_fields={
                    "type": SelectField(
                        label=Field.type.info["label"],
                        description=Field.type.info["description"],
                        choices=field_type_choices,
                    )
                },
            ),
        )
    ]

    @expose("/export-entries/<int:pk>")
    def export_entries(self, pk):
        """Taken from Flask-Admin with some modifications, no shame!"""
        form = self.get_one(str(pk))
        filename = "attachment; filename=%s" % _gen_csv_file_name(form)

        class Echo(object):
            """
            An object that implements just the write method of the file-like
            interface.
            """

            def write(self, value):
                """
                Write the value by returning it, instead of storing
                in a buffer.
                """
                return value

        writer = csv.writer(Echo())

        def generate():
            # Append the column titles at the beginning
            titles = [csv_encode("date")] + [
                csv_encode(field.name) for field in form.fields
            ]
            yield writer.writerow(titles)
            for entry in form.entries:
                vals = [csv_encode(entry.created.isoformat())] + [
                    csv_encode(_process_field_value(field)) for field in entry.fields
                ]
                yield writer.writerow(vals)

        return Response(
            stream_with_context(generate()),
            headers={"Content-Disposition": filename},
            mimetype="text/csv",
        )

    @expose("/view-entries/<int:pk>")
    def view_entries(self, pk):
        """View form entries"""
        form = self.get_one(str(pk))
        entries = FormEntry.query.filter_by(form=form)
        paginator = paginate_with_args(entries)
        return self.render(
            "oy_admin/form-entries.html",
            form=form,
            paginator=paginator,
            val_proc=_process_field_value,
        )
示例#13
0
class VendorForm(Form):
	name = TextField('Name:')
	vendor_type = SelectField('Type', choices=[('t1', 'Location')])
	description = TextField('Description:')
	address = TextField('Address:')
	contacts = TextField('Contacts:')
 class TestForm(Form):
     fruit = SelectField(**kwargs)
示例#15
0
class NewApplianceForm(FlaskForm):
    """Form to add new appliance"""

    name = StringField('Appliance', validators=[InputRequired()])
    watts = IntegerField('Watts', validators=[InputRequired()])
    category = SelectField('Category')
 class MyForm(Form):
     choice_field = SelectField(
         choices=[('', '-- Choose --'), ('choice 1', 'Something')],
         coerce=null_or_unicode
     )