class SignupForm2(ModelForm): email2 = HiddenField() email = EmailField(validators=[ DataRequired(), Email() # , # Unique( # User2.email, # get_session=lambda: db.session # ) ]) skills = StringField('Extra Curricular Activities', [DataRequired(), Length(3, 2000)]) train = StringField('Recent Trainings', [Length(3, 2000)]) fullname = StringField('Student Name', [DataRequired(), Length(3, 254)]) startdate = DateField('DatePicker', format='%Y-%m-%d') enddate = DateField('DatePicker', format='%Y-%m-%d') department = SelectField(u'School', choices=[('Donlon', 'Donlon Elementary'), ('Mohr', 'Mohr Elementary'), ('Fairlands', 'Fairlands Elementary'), ('Hearst', 'Hearst Elementary'), ('Stratford', 'Stratford Elementary'), ('Hart', 'Thomas Hart Middle School'), ('Harvest', 'Harvest Park Middle School') ]) protype = SelectField(u'Grade', choices=[('kinder', 'Kinder Garten'), ('first', 'First'), ('second', 'Second'), ('third', 'Third'), ('fourth', 'Fourth'), ('fifth', 'Fifth'), ('sixth', 'Sixth'), ('seventh', 'Seventh')])
class DitherForm(Form): instrument = HiddenField() observation = HiddenField() centre = BooleanField(u"Centre Dither on Detector V2/V3 Position") dither_type = SelectField() dither_points = SelectField() dither_size = SelectField() dither_subpixel = SelectField() dither_id = HiddenField(default='') sim_prefix = HiddenField() def __init__(self, *args, **kwargs): super(DitherForm, self).__init__(*args, **kwargs) self.dither_type.choices = self.get_dither_type self.dither_size.choices = self.get_dither_size self.dither_points.choices = self.get_dither_points self.dither_subpixel.choices = self.get_dither_subpixel def get_dither_type(self): return [ (x, x.title()) for x in DefaultSettings.instruments[self.instrument.data].DITHERS ] def get_dither_points(self): return [(x, x) for x in DefaultSettings.instruments[ self.instrument.data].DITHER_POINTS[self.dither_type.data]] def get_dither_size(self): return [(x, x.title()) for x in DefaultSettings.instruments[ self.instrument.data].DITHER_SIZE[self.dither_type.data]] def get_dither_subpixel(self): return [(x, x) for x in DefaultSettings.instruments[ self.instrument.data].DITHER_SUBPIXEL[self.dither_type.data]]
class BookForm(FlaskForm): BookTitle = StringField('Book Title', validators=[DataRequired(), Length(min=2, max=20)]) CoverTemplate = SelectField('Cover Template', choices=list((str(Templates[i]), ) * 2 for i in range(len(Templates))), validators=[DataRequired()]) # Font = SelectField('Font', choices=list((str(Fonts[i]),)*2 for i in range(len(Templates))), validators=[DataRequired()]) AuthorName = StringField( 'Author Name', validators=[DataRequired(), Length(min=2, max=20)]) BackgroundColor = ColorField('Background Color', validators=[DataRequired()]) Puplisher = StringField('Puplisher', validators=[DataRequired(), Length(min=2, max=20)]) PuplishingYear = SelectField('Puplishing Year', choices=list((str(2018 - i), ) * 2 for i in range(0, 50)), validators=[DataRequired()]) Generate = SubmitField('Generate')
class TrackGoalForm(FlaskForm): name = TextAreaField(_l(u'Goal Name'), validators=[DataRequired()]) #describe what your accomplishment will look like smart_description = TextAreaField(_l('Description')) #Enter the date when you plan to achieve your goal. Suggestion: It is more satisfying to achieve smaller goals in short periods of time, such as one to six months from today. #add logic: if date > then six months from today, give user pop-up message suggesting a shorter time frame. due_date = DateField(_l('Due Date', format='%Y-%m-%d')) #Does your goal fit into a particular dimension of your well-being? If so, select it below. dimension = SelectField(_l('Well-being Dimension'), choices=[('Environmental', 'Environmental'), ('Intellectual', 'Intellectual'), ('Financial', 'Financial'), ('Mental-Emotional', 'Mental-Emotional'), ('Occupational', 'Occupational'), ('Physical', 'Physical'), ('Social', 'Social'), ('Spiritual', 'Spiritual'), ], coerce=str, option_widget=None, validators=[DataRequired()]) #how will you know that you have accomplished the goal? #enter the number of units that will demonstrate you have successfully accomplished the goal #For example, if your goal is to lose weight, enter the number of pounds or kilos that you plan to lose. #If you want to achieve a specific GPA, enter the GPA number. #If you plan to complete an single event (run a 10k foot race or a marathon) or earn a single techincal certification, enter 1. unit_number = IntField(_l('Measurement Number'), validators=[Length(min=0, max=10)] #enter the type of measurement unit_type = SelectField(_l(u'Unit of Measurement'), choices=[('number', 'number'), ('lbs', 'lbs'), ('kg', 'kg'), ('hours', 'hours'), ('minutes', 'minutes'), ('GPA', 'GPA')], coerce=str, option_widget=None, validators=[DataRequired()]) done = SelectField(u'Complete?', choices=[('no', 'No'), ('yes', 'Yes'),]) submit = SubmitField(_l('Submit'))
class StellarForm(BaseForm): n_stars = IntegerField( u"Number of Stars", default=50000, validators=[validators.NumberRange(min=0, max=1000000000)]) z_low = FloatField(u"[Fe/H] Lower Bound", default=0.0, validators=[validators.NumberRange(min=-2.2, max=0.5)]) z_high = FloatField(u"[Fe/H] Upper Bound", default=0.0, validators=[ validators.NumberRange(min=-2.2, max=0.5), GreaterThan('z_low') ]) age_low = FormattedFloatField( u"Age Lower Bound", default=1.0e9, validators=[validators.NumberRange(min=1.e6, max=1.35e10)]) age_high = FormattedFloatField(u"Age Upper Bound", default=1.0e9, validators=[ validators.NumberRange(min=1.e6, max=1.35e10), GreaterThan('age_low') ]) imf = SelectField(u"IMF", default="salpeter", choices=imf_choices) alpha = FloatField(u"Power Law Order", default=-2.35, validators=[validators.NumberRange(min=-3., max=-1.)]) binary_fraction = FloatField( u"Binary Fraction", default=0.1, validators=[validators.NumberRange(min=0., max=1.)]) distribution = SelectField(u"Distribution", default="invpow", choices=distribution_choices) clustered = BooleanField(u"Move Higher-mass Stars Closer to Centre", default=True) radius = FloatField(u"Radius", default=10.0) radius_units = SelectField(u"Radius Units", default=u"pc", choices=[("pc", "pc"), ("arcsec", "arcsec")]) offset_ra = FloatField(u"RA Offset (mas)", default=0.0) offset_dec = FloatField(u"DEC Offset (mas)", default=0.0) distance_low = FloatField( u"Distance Lower Bound (kpc)", default=20.0, validators=[validators.NumberRange(min=1.e-3, max=4.2e6)]) distance_high = FloatField(u"Distance Upper Bound (kpc)", default=20.0, validators=[ validators.NumberRange(min=1.e-3, max=4.2e6), GreaterThan('distance_low') ]) stellar_id = HiddenField(default='') sim_prefix = HiddenField()
def buildDitherForm(sim, ins, obs, dither_type=None, dither_points=None, dither_size=None, dither_subpixel=None): class DitherForm(Form): pass DitherForm.instrument = HiddenField(default=ins) DitherForm.centre = BooleanField( u"Centre Dither Offsets on Detector V2/V3 Position", default=False) DitherForm.dither_id = HiddenField(default='') DitherForm.sim_prefix = HiddenField(default=sim) DitherForm.observation = HiddenField(default=obs) choices = [(x, x.title()) for x in DefaultSettings.instruments[ins].DITHERS] dither_type_default = choices[0][0] if dither_type is not None: dither_type_default = dither_type DitherForm.dither_type = SelectField(u"Dither Type", choices=choices, default=dither_type_default) choices = [ (x, x) for x in DefaultSettings.instruments[ins].DITHER_POINTS[dither_type_default] ] default = choices[0][0] if dither_points is not None and dither_points in [x[0] for x in choices]: default = dither_points DitherForm.dither_points = SelectField(u"Dither Points", choices=choices, default=default) choices = [ (x, x.title()) for x in DefaultSettings.instruments[ins].DITHER_SIZE[dither_type_default] ] default = choices[0][0] if dither_size is not None and dither_size in [x[0] for x in choices]: default = dither_size DitherForm.dither_size = SelectField(u"Dither Size", choices=choices, default=default) choices = [ (x, x) for x in DefaultSettings.instruments[ins].DITHER_SUBPIXEL[dither_type_default] ] default = choices[0][0] if dither_subpixel is not None and dither_subpixel in [ x[0] for x in choices ]: default = dither_subpixel DitherForm.dither_subpixel = SelectField(u"Subpixel Dither", choices=choices, default=default) return DitherForm()
class TaskForm(FlaskForm): name = TextAreaField(_l(u'Task Name'), validators=[DataRequired()]) priority = SelectField(_l('Priority'), choices=[('high', 'high'), ('medium', 'medium'), ('low', 'low')], validators=[DataRequired()]) due_date = DateField(_l('Due Date', format='%Y-%m-%d')) description = TextAreaField(_l('Description')) done = SelectField(u'Complete?', choices=[ ('no', 'No'), ('yes', 'Yes'), ]) submit = SubmitField(_l('Submit'))
def buildDepartTimesFieldFerry(departure, arrival, time): times = getListOfDepartureTimesFerry(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)
class SignUpForm(ModelForm): username = StringField('ID', [ DataRequired(message='ID는 필수 항목입니다.'), Length(min=4, max=20, message='%(min)d글자 이상 %(max)d글자 이하로 입력해주세요.'), Unique(UserModel.username, message='이미 존재하는 아이디입니다.') ]) password = PasswordField('Password', [ required(message='비밀번호는 필수 항목입니다.'), Length(min=6, max=20, message='%(min)d 이상 %(max)d 이하로 입력해주세요.') ]) confirm_password = PasswordField('Confirm Password', [ required(message='비밀번호 확인값은 필수 항목입니다.'), EqualTo('password', message='비밀번호와 비밀번호 확인값이 일치하지 않습니다.') ]) name = StringField('Name', [required(message='이름은 필수 항목입니다.')]) nickname = StringField('Nickname', [ required(message='닉네임은 필수 항목입니다.'), Length(min=4, max=16), Unique(UserModel.nickname, message='이미 존재하는 닉네임입니다.') ]) email = EmailField('Email', [ required(message='이메일은 필수 항목입니다.'), Email(message='유효한 이메일 주소를 입력해주세요.'), Unique(UserModel.email, message='이미 존재하는 이메일입니다.') ]) gender = SelectField('Gender', choices=[('male', '남자'), ('female', '여자')])
class GalaxyForm(BaseForm): n_gals = IntegerField(u"Number of Galaxies", default=100, validators=[validators.NumberRange(min=0, max=5000)]) z_low = FloatField(u"Redshift Lower Bound", default=0., validators=[validators.NumberRange(min=0., max=10.)]) z_high = FloatField(u"Redshift Upper Bound", default=0., validators=[ validators.NumberRange(min=0., max=10.), GreaterThan('z_low') ]) rad_low = FloatField( u"Half-light Radius Lower Bound", default=0.01, validators=[validators.NumberRange(min=1.e-3, max=10.)]) rad_high = FloatField(u"Half-light Radius Upper Bound", default=2., validators=[ validators.NumberRange(min=1.e-3, max=10.), GreaterThan('rad_low') ]) sb_v_low = FloatField( u"Apparent average surface brightness lower bound (Johnson,V)", default=40., validators=[ validators.NumberRange(min=15., max=45.), GreaterThan('sb_v_high') ]) sb_v_high = FloatField( u"Apparent average surface brightness upper bound (Johnson,V)", default=30., validators=[validators.NumberRange(min=15., max=45.)]) distribution = SelectField(u"Distribution", default="uniform", choices=distribution_choices) clustered = BooleanField(u"Move Higher-mass Galaxies Closer to Centre", default=False) radius = FloatField(u"Radius", default=600.0) radius_units = SelectField(u"Radius Units", default=u"pc", choices=[("pc", "pc"), ("arcsec", "arcsec")]) offset_ra = FloatField(u"RA Offset (arcsec)", default=0.0) offset_dec = FloatField(u"DEC Offset (arcsec)", default=0.0) galaxy_id = HiddenField(default='') sim_prefix = HiddenField()
class AddNapForm(FlaskForm): CHOICES_PROBLEMS = [ ('OK', 'Wszystko OK'), ('--', 'Płacz'), ('/', 'Krzyk'), ] CHOICES_PLACES = [ ('lozeczko', 'Łóżeczko'), ('spacer', 'Spacer'), ('rece', 'Ręce') ] cdate = DateField('Data:') stime = TimeField('Początek drzemki:') etime = TimeField('Koniec drzemki:') problems = SelectField('Problemy:', choices=CHOICES_PROBLEMS) place = SelectField('Miejsce uśnięcia:', choices=CHOICES_PLACES) notes = TextAreaField('Notatki:')
class BizPostForm(FlaskForm): business_name = StringField('Business Name:', validators=[DataRequired()], render_kw={"placeholder": "Business Name"}) desc = TextAreaField( 'Business Info:', validators=[DataRequired()], ) email = StringField('Email', validators=[DataRequired(), Email()], render_kw={"placeholder": "Email"}) address = StringField( 'Address:', validators=[DataRequired()], render_kw={"placeholder": "200 some St, Sydney CBD, 2000"}) phone = IntegerField( 'Phone:', render_kw={"placeholder": "0412 345 678 (if you want to be called)"}) menu = StringField('Menu: (website link)', render_kw={"placeholder": "www.example.com.au"}) food = BooleanField('Food:') booze = BooleanField('Booze:') pickup = BooleanField('Pickup:') selfd = BooleanField('Self Delivery:') uber = BooleanField('Uber Eats:') deliveroo = BooleanField('Deliveroo:') bopple = BooleanField('Bopple:') instagram = StringField('Instagram:', validators=[DataRequired()], render_kw={"placeholder": "@examplebar"}) facebook = StringField( 'Facebook:', validators=[DataRequired()], render_kw={"placeholder": "www.facebook.com/examplebar"}) spinfo = TextAreaField( 'Special Info:', validators=[DataRequired()], render_kw={"placeholder": "IE: DM on instagram to order"}) region = SelectField( u'Area:', choices=(('Sydney', (('SYD-CBD', 'CBD'), ('ES', 'Eastern Suburbs'), ('IW', 'Inner West'), ('SS', 'South Sydney'), ('NS', 'North Sydney'), ('NB', 'Northern Beaches'), ('WS', 'Western Sydney'))), ('Melbourne', (('MEL-CBD', 'CBD'), ('FR', 'Fitzroy'), ('CW', 'Collingwood'), ('SK', 'St. Kilda'))), ('Brisbane', ( ('BRIS-CBD', 'CBD'), ('VY', 'Valley'), ('RC', 'Red Cliffe'), ('RC', 'Red Cliffe'), )))) recaptcha = RecaptchaField() submit = SubmitField('Submit')
class EventForm(Form): name = TextField('Event name:') start_date = TextField('Start date:') end_date = TextField('End date:') event_type = SelectField('Type', choices=[('pl', 'product launching'), ('be', 'business event'), ('it', 'IT event'), ('cp', 'Christmas party')]) budget = IntegerField("Budget(in LEI RO ):", [validators.NumberRange(min=0, max=1000)]) nr_persons = IntegerField('Nr. of persons:') description = TextAreaField('Description:') scope = TextField("Scope:") submit = SubmitField('OK')
class SettingsForm(FlaskForm): choices = [(15, '15 minute'), (30,'30 minute'), (60, '60 minute')] """Meeting duration list [(dataValue, textLabel), (value, textLabel)]""" duration = SelectField('Choose a time',choices=choices) """Meeting duration""" timeRange = initTimeRange() "List of tuple of time such as [(0,'9:0AM'), (15,'9:15AM'), (30,'9:30AM'),... (240,'1:0PM'),...]" start_time = SelectField('Choose a time', choices=timeRange) """Start of working hour""" end_time = SelectField('Choose a time', choices=timeRange) """End of working hour""" emailconfirm = BooleanField('Email Confirmation?') """Email confirmation check box""" delete = SubmitField('Delete Account?') """Delete Account""" submit = SubmitField('Save Changes') """Submit to Save changes"""
class CreateMealForm(FlaskForm): first_i = HiddenField() second_i = HiddenField() third_i = HiddenField() fourth_i = HiddenField() title = StringField('Name of Meal', validators=[DataRequired()]) type_ = SelectField('Type of Meal', choices=[("Breakfast", "Breakfast"), ("Lunch", "Lunch"), ("Dinner", "Dinner")], validators=[DataRequired()])
class add_entryForm(Form): destination = SelectField(u'Select destination', choices=[('Allahabad Station', 'Allahabad Station'), ('PVR Vinayak', 'PVR Vinayak'), ('Civil Lines', 'Civil Lines'), ('Prayag Station', 'Prayag Station')]) date = DateField('Date', format='%Y-%m-%d') time = TimeField('Time') trainno = IntegerField('Enter Train No if travelling by Train', [validators.optional()])
class SelectFields(FlaskForm): projects = [('wikipedia', 'Wikipedia'), ('wikisource', 'Wikisource'), ('wikibooks', 'Wikibooks'), ('wikinews', 'Wikinews'), ('wikiquote', 'Wikiquote'), ('wiktionary', 'Wiktionary'), ('wikiversity', 'Wikiversity')] lang = [('as', 'Assamese'), ('bn', 'Bangla'), ('bh', 'Bhojpuri'), ('bpy', 'Bishnupriya Manipuri'), ('gu', 'Gujarati'), ('en', 'English'), ('hi', 'Hindi'), ('kn', 'Kannada'), ('ks', 'Kashmiri'), ('gom', 'Konkani'), ('mai', 'Maithili'), ('ml', 'Malayalam'), ('mr', 'Marathi'), ('ne', 'Nepali'), ('new', 'Newari'), ('or', 'Oriya'), ('pi', 'Pali'), ('pa', 'Punjabi'), ('sa', 'Sanskrit'), ('sat', 'Santali'), ('sd', 'Sindhi'), ('ta', 'Tamil'), ('te', 'Telugu'), ('tcy', 'Tulu'), ('ur', 'Urdu')] trproject = SelectField('Select Project', choices=projects, render_kw={"class": "form-control"}) trlang = SelectField('Select Language', choices=lang, render_kw={"class": "form-control"})
class RecallForm(BaseForm): prevsim = TextField(u"Recall Simulation: ", validators=[validators.Required()]) action = SelectField(u"Process by: ", default="Running Again", choices=[("Running Again", "Running Again"), ("Editing", "Editing"), ("Displaying Final Result", "Displaying Final Result")]) previous_id = HiddenField(default='') sim_prefix = HiddenField() field_order = ('prevsim', 'action', 'previous_id')
class ContactForm(Form): email = EmailField("Email", [DataRequired(), Length(3, 254)]) projectid = TextField("Project Name", [DataRequired(), Length(3, 254)]) description = TextAreaField("Description", [DataRequired(), Length(1, 2000)]) # skills = TextAreaField("Extra Curricular Activity", # [DataRequired(), Length(1, 2000)]) skills = TextAreaField("Extra Curricular Activity", [Length(1, 2000)]) department = SelectField(u'School', choices=[ ('Donlon','Donlon Elementary'),('Mohr','Mohr Elementary'),('Fairlands','Fairlands Elementary'),('Hearst','Hearst Elementary') ,('Stratford','Stratford Elementary'),('Hart','Thomas Hart Middle School'),('Harvest','Harvest Park Middle School')]) protype = SelectField(u'Grade', choices=[('kinder','Kinder Garten'),('first','First'), ('second','Second'), ('third','Third'),('fourth','Fourth'), ('fifth','Fifth'),('sixth','Sixth'), ('seventh','Seventh')]) startdate = DateField('DatePicker', format='%Y-%m-%d') enddate = DateField('DatePicker', format='%Y-%m-%d')
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)
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"))
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"""
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')
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")
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
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()])
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")
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, )