class DatesForm(FlaskForm): parse_kwargs = {'yearfirst': True, 'dayfirst': False} display_format = '%m/%d/%Y %H:%M' render_kw = {'type': 'datetime-local'} deadline = DateTimeField('Survey deadline', parse_kwargs=parse_kwargs, display_format=display_format, render_kw=render_kw, validators=[DataRequired()]) reminder1 = DateTimeField('First student reminder (optional)', parse_kwargs=parse_kwargs, display_format=display_format, render_kw=render_kw) reminder2 = DateTimeField('Second student reminder (optional)', parse_kwargs=parse_kwargs, display_format=display_format, render_kw=render_kw) reminder3 = DateTimeField('Third student reminder (optional)', parse_kwargs=parse_kwargs, display_format=display_format, render_kw=render_kw) submit = SubmitField('Save') def validate_deadline(self, deadline): # compare submitted deadline to current time if not is_valid_datetime(self.deadline.data, datetime.utcnow()): raise ValidationError( 'Invalid deadline: make sure to set a deadline after the current time' )
class NewBookingFormBase(IndicoForm): start_dt = DateTimeField('Start date', validators=[InputRequired()], parse_kwargs={'dayfirst': True}, display_format='%d/%m/%Y %H:%M') end_dt = DateTimeField('End date', validators=[InputRequired()], parse_kwargs={'dayfirst': True}, display_format='%d/%m/%Y %H:%M') repeat_frequency = RadioField('Repeat frequency', coerce=int, default=0, validators=[InputRequired()], choices=[(0, _('Once')), (1, _('Daily')), (2, _('Weekly')), (3, _('Monthly'))]) repeat_interval = IntegerField('Repeat interval', validators=[NumberRange(0, 3)], default=0) def validate_repeat_interval(self, field): if (self.repeat_frequency.data, self.repeat_interval.data) not in RepeatMapping.mapping: raise ValidationError('Invalid repeat step') def validate_start_dt(self, field): if field.data != field.object_data and field.data.date() < date.today() and not session.user.is_admin: raise ValidationError(_('The start time cannot be in the past.')) def validate_end_dt(self, field): start_dt = self.start_dt.data end_dt = self.end_dt.data if start_dt.time() >= end_dt.time(): raise ValidationError('Invalid times') if self.repeat_frequency.data == RepeatFrequency.NEVER: field.data = datetime.combine(start_dt.date(), field.data.time()) elif start_dt.date() >= end_dt.date(): raise ValidationError('Invalid period')
class QsoForm(BaseQsoForm): date = DateTimeField("Date", default=datetime.datetime.utcnow, display_format="%Y-%m-%d") time = DateTimeField("Time", default=foo_bar_baz_qux, display_format="%H:%M:%S")
class HappyHourForm(FlaskForm): """ Form for admin to add or edit a happy hour """ day = SelectField("Day", choices=DAY_OPTIONS) start_time = DateTimeField('Start Time', display_format='%I:%M %p') end_time = DateTimeField('End Time', display_format='%I:%M %p') submit = SubmitField('submit')
class PostForm(Form): description = TextField('I\'m looking for...', validators=[Required()]) latitude = HiddenField(validators=[Required()]) longitude = HiddenField(validators=[Required()]) location = TextField('Location', validators=[Required(), Length(max=80)]) start_time = DateTimeField('Start Time') end_time = DateTimeField('End Time', validators=[Optional()]) expire_time = DateTimeField('Expire Time', validators=[Optional()]) submit = SubmitField('Look for others')
class ShiftForm(FlaskForm): ''' This is the form that displays fields to make a shift ''' role = SelectField('Role', validators=[validators.required()]) start = DateTimeField('Shift Starting Time', validators=[validators.required()]) end = DateTimeField('Shift Ending Time', validators=[validators.required()]) submit = SubmitField("Add Shift")
class _DateTimePair(Form): start = DateTimeField(_(u'from'), [UsedIf(lambda form, field: form.end.data)], display_format='%d/%m/%Y %H:%M', parse_kwargs={'dayfirst': True}) end = DateTimeField(_(u'to'), [UsedIf(lambda form, field: form.start.data)], display_format='%d/%m/%Y %H:%M', parse_kwargs={'dayfirst': True}) def validate_start(self, field): if self.start.data and self.end.data and self.start.data >= self.end.data: raise ValidationError('The start date must be earlier than the end date.') validate_end = validate_start
class EventForm(Form): """This class contains form fields for the Create Event form.""" currentDate = date.today() today = currentDate.strftime('%m/%d/%Y') event_name = fields.StringField('Name your event:', validators=[validators.InputRequired()]) description = fields.TextAreaField('Event description:', validators=[validators.InputRequired()]) category = fields.SelectField('Event category:', choices=[ ('hobbies-crafts', 'Arts & Crafts'), ('beliefs', 'Beliefs'), ('book-clubs', 'Book Clubs'), ('career-business', 'Career & Business'), ('education', 'Education'), ('fashion-beauty', 'Fashion & Beauty'), ('film', 'Film'), ('food', 'Food'), ('arts-culture', 'General Arts & Culture'), ('language', 'Language'), ('music', 'Music'), ('outdoors-adventure', 'Outoors Adventures'), ('parents-family', 'Parenting & Family'), ('social', 'Social'), ('sports-fitness', 'Sports & Fitness'), ('tech', 'Technology'), ], validators=[validators.InputRequired()]) formatted_address = fields.StringField('Location Address:', validators=[validators.InputRequired()]) start_date = DateTimeField('When will it start?', display_format='%Y-%m-%d %H:%M', validators=[validators.InputRequired()], render_kw={'type': 'datetime-local'}) end_date = DateTimeField('When will it end?', display_format='%Y-%m-%d %H:%M', validators=[validators.InputRequired()], render_kw={'type': 'datetime-local'}) cap = \ fields.IntegerField('Maximum number of people able to participate:' , validators=[]) attending = \ fields.IntegerField('How many people are attending already?', validators=[]) # location parsing fields (hidden) lat = fields.StringField('Latitude:') lng = fields.StringField('Longitude:') name = fields.StringField('Location Name:') address_2 = fields.StringField('Address Line 2:') postal_code = fields.StringField('Zip code:') sublocality = fields.StringField('City:') administrative_area_level_1_short = fields.StringField('State:')
class EntryForm(Form): title = TextField('Title', [validators.Length(min=1, max=255, message="You must provide a title")]) body = TextAreaField('Body', [validators.Length(min=4, max=1048576, message="The body is required")]) time = DateTimeField('Time', display_format="%H:%M") date = DateTimeField('Date', display_format="%m/%d/%Y") tags = TextField('Tags') is_draft = BooleanField('Draft?') is_deleted = BooleanField('Delete?') post_id = IntegerField('id', widget=HiddenInput())
class AppSettingsForm(Form): """ Settings of an experiemnt """ systemDate = DateTimeField("date", display_format='%Y-%m-%d %H:%M:%S %z', default=datetime.datetime.now)
class EditPollForm(FlaskForm): title = TextField(lazy_gettext("Title"), validators=[Required(), Length(min=3, max=80)]) description = TextAreaField(lazy_gettext("Description")) due_date = DateTimeField(lazy_gettext("Due date"), validators=[Optional()]) anonymous_allowed = BooleanField(lazy_gettext("Allow anonymous votes")) require_login = BooleanField(lazy_gettext("Require login to vote")) require_invitation = BooleanField(lazy_gettext("Require invitation to vote (requires login)")) public_listing = BooleanField(lazy_gettext("Show in public poll list")) one_vote_per_user = BooleanField(lazy_gettext("One vote per user (only effective with login)")) allow_comments = BooleanField(lazy_gettext("Allow comments")) show_invitations = BooleanField(lazy_gettext("Show invitations as empty votes")) owner_id = SelectField(lazy_gettext("Ownership"), choices=[(0, "Nobody")], coerce=int) timezone_name = SelectField(lazy_gettext("Timezone"), choices=[("", lazy_gettext("Coordinated time"))] + [(c, c) for c in common_timezones]) # password = TextField("Password") # password_level = SelectField("Password mode", choices=[ # (0, "Do not use password"), # (1, "Password required for editing"), # (2, "Password required to vote"), # (3, "Password required to show poll")], # coerce=int) show_results = SelectField(lazy_gettext("Results display"), choices=[ ("complete", lazy_gettext("show all votes")), ("summary", lazy_gettext("show only summary")), ("never", lazy_gettext("Do not show results")), ("complete_after_vote", lazy_gettext("Show all votes, but only after voting")), ("summary_after_vote", lazy_gettext("Show summary, but only after voting"))]) send_mail = BooleanField(lazy_gettext("Send mail to participants about results"))
class AuctionForm(Form): title = StringField('Title', [ validators.InputRequired( message=(u'You must supply an auction title.')), validators.Length( min=5, max=100, message=( u'A title must be atleast 5 and no more than 100 characters.')) ]) description = TextAreaField('Description', [ validators.InputRequired( message=(u'You must supply an auction description.')), validators.Length(min=15, message=(u'A title must be atleast 15 characters.')) ]) #tags = db.ListField(db.StringField(max_length=100, required=True)) expiration = DateTimeField("Expiration", [ validators.InputRequired( message=(u'You must supply an auction expiration time.')) ]) min_price = DecimalField("Minimum Price", places=2) isPublic = BooleanField("List publicly") group = StringField("Publicity: Group Name") submit = SubmitField('Create Auction')
class NewContractForm(FlaskForm): '''Form for starting new work on a contract through conductor Attributes: description: The contract's description flow: The :py:class:`~purchasing.data.flows.Flow` the contract should follow assigned: The :py:class:`~purchasing.users.models.User` the contract should be assigned to department: The :py:class:`~purchasing.users.models.Department` the contract should be assigned to start: The start time for the first :py:class:`~purchasing.data.contract_stages.ContractStage` for the contract ''' description = TextField(validators=[DataRequired()]) flow = QuerySelectField(query_factory=Flow.nonarchived_query_factory, get_pk=lambda i: i.id, get_label=lambda i: i.flow_name, allow_blank=True, blank_text='-----') assigned = QuerySelectField(query_factory=User.conductor_users_query, get_pk=lambda i: i.id, get_label=lambda i: i.email, allow_blank=True, blank_text='-----') department = QuerySelectField(query_factory=Department.query_factory, get_pk=lambda i: i.id, get_label=lambda i: i.name, allow_blank=True, blank_text='-----') start = DateTimeField(default=get_default)
class RequestForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) description = StringField('Description', validators=[DataRequired()]) client_id = SelectField('Client', validators=[DataRequired()], coerce=int) client_priority = SelectField('Client Priority', validators=[DataRequired()], coerce=int) target_date = DateTimeField('Target Date', validators=[ DateRange(min=datetime.today(), max=datetime.today() + relativedelta(years=65)) ]) product_area_code = SelectField('Product Area', validators=[DataRequired()], coerce=str) def validate_title(self, field): if FeatureRequest.query.filter( FeatureRequest.client_id == self.client_id.data, FeatureRequest.title == field.data, FeatureRequest.product_area_code == self.product_area_code.data).count() > 0: raise ValidationError("Record already exist for matching Client") def validate_client_id(self, field): if not Client.query.get(field.data): raise ValidationError("Invalid Client Selected") def validate_product_area_code(self, field): if not ProductArea.query.get(field.data): raise ValidationError("Invalid Product Area Selected")
class CompleteForm(FlaskForm): '''Form to hold the completion times Attributes: complete: Field to hold the date/time for when to complete a certain :py:class:`~purchasing.data.contract_stages.ContractStage` maximum: (instance variable) The current utc time Arguments: started: Datetime of what the minimum time should be, such as when the :py:class:`~purchasing.data.contract_stages.ContractStage` started. Because the ``complete`` form attribute uses the :py:func:`~purchasing.conductor.validators.validate_date` validator, passing a minumim is important to ensure the validator works properly (if you want to make sure that :py:class:`~purchasing.data.contract_stages.ContractStage` objects don't end before they start. Optional to allow the first stage in a give :py:class:`~purchasing.data.flows.Flow` to start in the past. ''' complete = DateTimeField(validators=[validate_date]) def __init__(self, started=None, *args, **kwargs): super(CompleteForm, self).__init__(*args, **kwargs) self.started = started.replace(second=0, microsecond=0) if started else None self.maximum = datetime.datetime.utcnow()
class SettingsForm(Form): """ Settings of an experiemnt """ rpi = RpiModule() desc = TextAreaField(u"Description:", validators=[Optional()], description='about this experience') start = DateTimeField("start", display_format='%Y-%m-%d %H:%M:%S %z', default=datetime.datetime.now) end = DateTimeField("end", display_format='%Y-%m-%d %H:%M:%S %z', default=datetime.datetime.now) interval = IntegerField("interval", default=360, description= 'Interval (in minutes)') ir = BooleanField("ir", default=True, description="Turn the infrared lights on/off") cameras = SelectMultipleField('cameras', choices= [(cam,"Camera%s"%cam) for cam in Config.CAMS], default=[1], coerce=int, description= 'Cameras to use') camera = rpi.selector.get_camera() def validate_cameras(form, field): """ validate function for the choice of cameras At list one camera should be selected Args: form : Form The form to check field : Field The field to check """ if len(field.data) < 1: raise ValidationError("Select at least one camera")
class NewHomeworkForm(FlaskForm): title = StringField( 'Homework Title:', validators=[InputRequired(message='Please enter a title')]) due_date = DateTimeField( 'Due Date:', display_format='%Y-%m-%d %H:%M', validators=[InputRequired(message='Please enter a due date')])
class EntryForm(Form): title = StringField(u'Title', validators=[validators.Optional()]) published = DateTimeField(u'Published', display_format='YYYY/MM/DD hh:mm:ss', validators=[validators.Optional()]) updated = DateTimeField(u'Updated', display_format='YYYY/MM/DD hh:mm:ss', validators=[validators.Optional()]) content = TextAreaField(u'Content', validators=[validators.Optional()]) summary = TextAreaField(u'Summary', validators=[validators.Optional()]) feed = SelectField(u'Feed', validators=[validators.InputRequired()], coerce=int) authors = SelectMultipleField(u'Authors', validators=[validators.Optional()], coerce=int) ping = BooleanField(u'Ping Hub', default=True)
class SearchRoomsForm(IndicoForm): location = QuerySelectField(_(u'Location'), get_label=lambda x: x.name, query_factory=Location.find, allow_blank=True) details = StringField() available = RadioField(_(u'Availability'), coerce=int, default=-1, widget=ConcatWidget(prefix_label=False), choices=[(1, _(u'Available')), (0, _(u'Booked')), (-1, _(u"Don't care"))]) capacity = IntegerField(_(u'Capacity'), validators=[Optional(), NumberRange(min=0)]) available_equipment = IndicoQuerySelectMultipleCheckboxField( _(u'Equipment'), get_label=_get_equipment_label, modify_object_list=_group_equipment, query_factory=lambda: EquipmentType.find().order_by(EquipmentType.name )) is_only_public = BooleanField(_(u'Only public rooms'), default=True) is_auto_confirm = BooleanField(_(u'Only rooms not requiring confirmation'), default=True) is_only_active = BooleanField(_(u'Only active rooms'), default=True) is_only_my_rooms = BooleanField(_(u'Only my rooms')) # Period details when searching for (un-)availability start_dt = DateTimeField(_(u'Start date'), validators=[Optional()], parse_kwargs={'dayfirst': True}, display_format='%d/%m/%Y %H:%M', widget=HiddenInput()) end_dt = DateTimeField(_(u'End date'), validators=[Optional()], parse_kwargs={'dayfirst': True}, display_format='%d/%m/%Y %H:%M', widget=HiddenInput()) repeatability = StringField( ) # TODO: use repeat_frequency/interval with new UI include_pending_blockings = BooleanField( _(u'Check conflicts against pending blockings'), default=True) include_pre_bookings = BooleanField( _(u'Check conflicts against pre-bookings'), default=True)
class ReservationForm(FlaskForm): ''' This is the form that displays fields to make a reservation ''' name = StringField('Name', [validators.Length(min=2, max=25)]) num = IntegerField('Guests', [validators.NumberRange(min=1, max=None)]) # phone = StringField('Phone Number', [validators.Length(min=10, max=10)]) phone = PhoneNumberField('Phone Number', [validators.DataRequired()]) length = IntegerField('Reservation Length(Minutes)', [validators.NumberRange(min=30, max=None)]) start = DateTimeField('Time and Date')
class VoteCreationForm(Form): """Form for creating/editing a new vote""" title = StringField('Vote title', validators=[DataRequired()]) description = TextAreaField('Description', validators=[DataRequired()]) start = DateTimeField('Start date', validators=[DataRequired()]) end = DateTimeField('End date', validators=[DataRequired()]) winners = IntegerField('Number of winners') system = SelectField('Voting System', choices=VOTE_SYSTEMS, coerce=int, default=2) def validate_start(self, field): """Verify that the start date is in the future""" if field.data <= datetime.datetime.utcnow(): raise ValidationError('Start time must be in the future') def validate_end(self, field): """Verify that the end date is in the future and after the start""" if field.data <= datetime.datetime.utcnow(): raise ValidationError('End time must be in the future') if field.data <= self.start.data: raise ValidationError('End time must be after start time')
class RunForm(FlaskForm): person = SelectField("Person", coerce=int) time = DateTimeField( "Time of Run", [validators.Required()], # Ensure the time has a timezone attached (note numerical format # works, the name does not). display_format="%Y/%m/%d %H:%M %z") cafeid = SelectField("Cafe", coerce=int) pickup = TextField("Pickup Location") is_open = BooleanField("Currently accepting coffees")
class ModelParamsForm(FlaskForm): intervalfield = SelectField('Inteval', choices=[(1, '1 minute'), (5, '5 minutes'), (10, '10 minutes'), (15, '15 minutes'), (30, '30 minutes'), (60, '1 hour')], default=10) startfield = DateTimeField(default=datetime.utcnow() - timedelta(days=3)) durationfield = FloatField('Duration (days)', default=7) lonfield = FloatField('Longitude', default=262.25) latfield = FloatField('Latitude', default=30.28) elevationfield = FloatField('Elevation', default=190.)
class AdvSearchForm(Form): # Remember that the Full Text Search already search text within: # Call, Comment, Country, Email, Name, Notes, Operator, # Owner callsign, Qslmsg, Station callsign, Web and Qsl comment # Select inputs will have a first field "Any" value "any" from_date = DateTimeField("From date", [Optional()]) to_date = DateTimeField("To date", [Optional()]) fts = StringField("Search string", [Optional()]) country = SelectField(label="Country", validators=[Optional()]) call = StringField("Callsign", [Optional()]) mode = SelectField(label="Mode", validators=[Optional()]) band = SelectField(label="Band", validators=[Optional()]) frequency = IntegerField("Freq", [Optional()]) pictures = SelectField(label="Has pictures", validators=[Optional()], choices=[["any", "Any"], ["Y", "Yes"], ["N", "No"]]) # qsl statues <select> # eqsl statues <select> # pictures <select> submit = SubmitField("Search")
class EditQsoForm(BaseQsoForm): time_on = DateTimeField("Start date", display_format="%Y-%m-%d %H:%M:%S", validators=[DataRequired()]) time_off = DateTimeField("End date", display_format="%Y-%m-%d %H:%M:%S", validators=[DataRequired()]) notes = TextAreaField("Notes") qsl_rcvd = SelectField( "QSL Received", choices=[["N", "No"], ["Y", "Yes"], ["R", "Requested"], ["I", "Invalid (Ignore)"], ["V", "Verified (Match)"]], ) qsl_rcvd_via = SelectField( "Received via", choices=[["", "Method"], ["D", "Direct"], ["B", "Bureau"], ["E", "Electronic"], ["M", "Manager"]], ) eqsl_qsl_rcvd = SelectField( "eQSL Received", choices=[["N", "No"], ["Y", "Yes"], ["R", "Requested"], ["I", "Invalid (Ignore)"], ["V", "Verified (Match)"]], ) lotw_qsl_rcvd = SelectField( "LOTW QSL Received", choices=[["N", "No"], ["Y", "Yes"], ["R", "Requested"], ["I", "Invalid (Ignore)"], ["V", "Verified (Match)"]], ) lotw_qsl_sent = SelectField( "LOTW QSL Sent", choices=[["N", "No"], ["Y", "Yes"], ["R", "Requested"], ["Q", "Queued"], ["I", "Invalid (Ignore)"]], )
class PostForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) slug = StringField('Slug') body = TextAreaField('Body', validators=[DataRequired()]) published = BooleanField('Published') published_at = DateTimeField('Publish time (in UTC)', display_format='%Y-%m-%dT%H:%M', validators=[Optional()]) tag_names = StringField('Tags (comma separated)') def to_post(self, user=None): tags = self._find_or_build_tags() published_at = self._get_published_at() return Post( title=self.title.data, slug=self.slug.data, body=self.body.data, published_at=published_at, user=user, tags=tags, ) def update_post(self, post): post.title = self.title.data post.slug = self.slug.data post.body = self.body.data post.tags = self._find_or_build_tags() post.published_at = self._get_published_at() def _find_or_build_tags(self): if not self.tag_names.data: return [] requested_tags = [ Tag(name=t.strip()) for t in self.tag_names.data.split(',') ] tags = Tag.query.filter( Tag.slug.in_([tag.slug for tag in requested_tags])).all() found_tag_slugs = [tag.slug for tag in tags] for tag in requested_tags: if tag.slug not in found_tag_slugs: tags.append(tag) return tags def _get_published_at(self): if self.published_at.data: return self.published_at.data if self.published.data: return datetime.utcnow() return None
class TaskForm(Form): title = StringField(lazy_gettext('Title'), validators=[DataRequired()]) description = PageDownField(lazy_gettext('Description')) worker = SelectField(lazy_gettext('Worker'), coerce=int) price = DecimalField(lazy_gettext('Price')) timelimit = DateTimeField(lazy_gettext('Timelimit'), display_format='%d.%m.%Y %H:%M') submit = SubmitField(lazy_gettext('Submit')) def __init__(self, *args, **kwargs): super(TaskForm, self).__init__(*args, **kwargs) self.worker.choices = [ (user.id, user.fullname) for user in User.query.order_by(User.fullname).all() ]
class EventForm(FormBase): title = StringField() description_short = StringField() description = StringField() max_participants = IntegerField() participants = FieldList(StringField()) rewards = FieldList(IntegerField()) best_player_reward = IntegerField() date_start = DateTimeField(display_format='%d/%m/%Y %H:%M') image_big = StringField()
class PollForm(Form): title = TextField(lazy_gettext("Title"), validators=[Required(), Length(min=3, max=80)]) slug = TextField( lazy_gettext("URL name"), validators=[ Optional(), Length(min=3, max=80), Regexp(r"^[a-zA-Z0-9_-]*$", message=lazy_gettext("Invalid character.")), UniqueObject(Poll, "slug", dict(deleted=False), message=lazy_gettext( "A poll with this URL name already exists.")), NoneOf(Poll.RESERVED_NAMES, message=lazy_gettext("This is a reserved name.")) ]) due_date = DateTimeField(lazy_gettext("Due date"), validators=[Optional()])
class CreateEventForm(FlaskForm): title = StringField( 'title', validators=[ InputRequired(message="Event title cannot be empty."), ], render_kw={'autofocus': True}) country = StringField( 'country', validators=[ InputRequired(message="You must specify the country of the even."), ]) region = StringField('region') city = StringField('city') address_1 = StringField( 'address_1', validators=[ InputRequired(message="You must supply an address field."), ]) address_2 = StringField('address_2', ) event_date = DateTimeField( 'event_date', validators=[ InputRequired(message="You must specify the date of the event."), ]) description = StringField( 'description', validators=[ InputRequired(message="Description cannot be empty."), ], widget=TextArea()) submit = SubmitField('Create Event')