class UserForm(ModelForm): #pylint: disable=no-init,too-few-public-methods ''' Form for users to edit their profile ''' class Meta: #pylint: disable=no-init,missing-docstring,old-style-class,too-few-public-methods model = User only = [ 'first_name', 'last_name', 'position', 'organization', 'organization_type', 'city', 'country', 'projects' ] field_args = { 'first_name': { 'validators': [Required()] }, 'last_name': { 'validators': [Required()] }, } picture = FileField(label=lazy_gettext('User Picture'), description='Optional', validators=[image_validator]) locales = CallableChoicesSelectMultipleField( label=lazy_gettext('Languages'), widget=Select(multiple=True), choices=lambda: [(l.language, l.get_display_name()) for l in LOCALES]) expertise_domain_names = CallableChoicesSelectMultipleField( label=lazy_gettext('Fields of Work'), widget=Select(multiple=True), choices=lambda: [(v, lazy_gettext(v)) for v in current_app.config['DOMAINS']])
class CreateStaffForm(Form): year = SelectField(u'Year', widget=Select(), choices=YEARS) staff_id = StringField(u'Staff Identifier', widget=TextInput(), validators=[validators.input_required()]) first_name = StringField(u'First Name', widget=TextInput(), validators=[validators.input_required()]) last_name = StringField(u'Last Name', widget=TextInput(), validators=[validators.input_required()]) title = SelectField(u'Title', widget=Select(), choices=(('Mr','Mr'),('Mrs','Mrs'),('Miss','Miss'),('Ms','Ms'))) subject = StringField(u'Subject', widget=TextInput(),validators=[validators.input_required()]) email = StringField(u'Email', widget=TextInput(), validators=[validators.Email()])
class SearchForm(Form): ''' Form for searching the user database. ''' country = CountryField() locales = CallableChoicesSelectMultipleField( widget=Select(multiple=True), choices=lambda: [(l.language, l.get_language_name(get_locale())) for l in LOCALES]) expertise_domain_names = CallableChoicesSelectMultipleField( widget=Select(multiple=True), choices=lambda: [(v, lazy_gettext(v)) for v in current_app.config['DOMAINS']])
class ServiceSlotForm(ModelForm): class Meta: model = HealthServiceTimeSlot service = QuerySelectField(label='Service', validators=[Required()], widget=Select(), query_factory=lambda: HealthServiceService.query.all(), get_label='name', blank_text='Please specify the service') site = QuerySelectField(label='Site', validators=[Required()], widget=Select(), query_factory=lambda: HealthServiceSite.query.all(), get_label='name', blank_text='Please specify the site')
class VerificationForm(Form): student = StringField(u'Student Name (Full Name)', widget=TextInput(),validators=[validators.input_required(message=NO_INPUT_ERROR), validators.length(max=MAX_LENGTH)]) verifier_name = StringField(u'Teacher name (Verifier)', widget=TextInput(),validators=[validators.input_required(message=NO_INPUT_ERROR), validators.length(max=MAX_LENGTH)]) verifier_school = StringField(u'School of Verifier', widget=TextInput()) verifier_school_other = StringField(u'Other - School of Verifier', widget=TextInput()) verifiers_grade = StringField(u'Assessment judgement of Verifier', widget=TextInput()) markers_grade = SelectField(u'Markers assessment judgement', widget=Select(), choices=GRADES) reported_grade = SelectField(u'Reported assessment judgement', widget=Select(), choices=GRADES) tic = AllStaffData(u'Teacher in Charge', widget=Select()) discussion = StringField(u'Discussion', widget=TextArea())
class Task(TimestampMixin, AuthorMixin, db.Model): __tablename__ = 'tasks' id = db.Column(db.Integer, primary_key=True) summary = db.Column(db.String(120), info={ 'label': lazy_gettext('Summary'), 'validators': InputRequired() }) description = db.Column(db.String(1000), info={ 'label': 'Description', 'widget': TextArea() }) due = db.Column(db.DateTime, info={'label': lazy_gettext('Due')}) priority = db.Column(ChoiceType(CHOICES_PRIORITY), info={'label': lazy_gettext('Priority')}, nullable=False) status = db.Column(ChoiceType(CHOICES_STATUS), info={'label': lazy_gettext('Status')}, nullable=False) assigned = db.relationship('User', secondary=rel_users_tasks, backref='tasks', info={ 'choices': [], 'label': lazy_gettext('Assigned User'), 'widget': Select() }) _contacts = db.relationship('Contact', secondary=rel_contacts_tasks, backref='contacts', info={ 'choices': [], 'label': lazy_gettext('Related Contact'), 'widget': Select() }) comments = db.relationship('Comment', backref='tasks', lazy=True) def add_user(self, user): self.assigned.append(user) def remove_user(self, user): self.assigned.remove(user) def add_contact(self, contact): self._contacts.append(contact) def remove_contact(self, contact): self._contacts.remove(contact)
class StandardCreateForm(Form): year = SelectField(u'Year', widget=Select(), choices=YEARS) verification_total = IntegerField(u'No of Student Entries', widget=TextInput(), validators=[validators.optional()]) subject_id = StringField(u'Subject ID e.g MUS1', widget=TextInput(), validators=[validators.input_required(message=NO_INPUT_ERROR),validators.length(max=MAX_LENGTH)]) subject_title = StringField(u'Faculty Umbrella e.g Arts', widget=TextInput(), validators=[validators.input_required(message=NO_INPUT_ERROR),validators.length(max=MAX_LENGTH)]) standard_no = StringField(u'Standard Number', widget=TextInput(), validators=[validators.input_required(message=NO_INPUT_ERROR),validators.length(max=MAX_LENGTH)]) version = StringField(u'Version of the Standard', widget=TextInput(), validators=[validators.input_required(message=NO_INPUT_ERROR),validators.length(max=MAX_LENGTH)]) level = SelectField(u'NCEA level of Standard', widget=Select(), choices=[('Multi','Multi'),('1','1'),('2','2'),('3','3')]) credits = IntegerField(u'Credits <br><small>How many credits the standard is worth</small>', widget=TextInput(),validators=[validators.input_required(message=NO_INPUT_ERROR),validators.NumberRange(min=1,max=50,message="Please enter a Number : Max 50")]) title = StringField(u'Title of the standard', widget=TextArea(), validators=[validators.input_required(message=NO_INPUT_ERROR)]) standard_type = SelectField(u'Standard Type <br><small>Achievement or Unit Standard</small>',widget=Select(),choices=(('Achievement Standard','Achievement Standard'),('Unit Standard','Unit Standard'))) tic = AllStaffData(u'Teacher in Charge', widget=Select())
class BoundSpecForm(Form): """Show mostly static info about a spec registered to a component""" id = HiddenField("Spec ID") name = StringField("Name", [validators.required()], widget=StaticIfExists(), render_kw={'class':'form-control'}) category = NoValSelectField("Category", render_kw={'class':'form-control'}, choices=copy(spectypes), widget=StaticIfExists(Select())) distribution = StringField("Dist.", default=(emissionspec.EmissionSpec. _default_distribution), widget=StaticIfExists(dist_widget), render_kw={'class':'form-control'}) #rate = StaticField("Rate", default='') querymod = JSONField("Querymod",render_kw={'class':'form-control'}) #edit = StaticField("Edit", default="edit") #override populate_obj to make new spec if necessary def populate_obj(self, obj): spec = self.id.data if not spec or spec == str(None): spec = emissionspec.buildspecfromdict({ '__class__': self.category.data, 'name': self.name.data, 'distribution': self.distribution.data, }) obj.spec = spec obj.querymod = self.querymod.data
class IndicoEnumSelectField(_EnumFieldMixin, SelectFieldBase): """Select field backed by a :class:`TitledEnum`""" widget = Select() def __init__(self, label=None, validators=None, enum=None, sorted=False, only=None, skip=None, none=None, titles=None, **kwargs): super(IndicoEnumSelectField, self).__init__(label, validators, **kwargs) self.enum = enum self.sorted = sorted self.only = set(only) if only is not None else None self.skip = set(skip or set()) self.none = none self.titles = titles def iter_choices(self): items = ( x for x in self.enum if x not in self.skip and (self.only is None or x in self.only)) if self.sorted: items = sorted(items, key=attrgetter('title')) if self.none is not None: yield ('__None', self.none, self.data is None) for item in items: title = item.title if self.titles is None else self.titles[item] yield (item.name, title, item == self.data)
class SignupForm(FlaskForm): def check_phone(self, phone): if not re.search(r'.*[0-9]{3}\D?[0-9]{3}\D?[0-9]{4}\D?', str(phone)): raise ValidationError('Invalid phone number') def check_email_exists(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('The email is already signed up.') def check_phone_exists(self, phone): user = User.query.filter_by(phone=phone.data).first() if user: raise ValidationError('The phone is already signed up.') roles = ['Owner', 'CEO', 'Representative'] first_name = StringField('First Name', validators=[DataRequired(), Length(min=2, max=40)]) last_name = StringField('Last Name', validators=[DataRequired(), Length(min=2, max=40)]) email = StringField('Email', validators=[DataRequired(), Email(), check_email_exists]) phone = StringField('Phone', validators=[DataRequired(), check_phone, check_phone_exists]) password = PasswordField('Password', validators=[DataRequired()]) conf_pass = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) role = Select('Role in organization') submit_step_1 = SubmitField('Next')
class InsideVerificationForm(Form): standard = StringField(u'Standard', widget=HiddenInput()) student = StringField(u'Student Name (Full Name)', widget=TextInput(),validators=[validators.input_required(message=NO_INPUT_ERROR)]) verifier_name = StringField(u'Teacher name (Verifier)', widget=TextInput(),validators=[validators.input_required(message=NO_INPUT_ERROR)]) verifier_school = StringField(u'School of Verifier', widget=TextInput()) verifier_school_other = StringField(u'Other - School of Verifier', widget=TextInput()) verifiers_grade = SelectField(u'Assessment Judgement of Verifier', widget=Select(), choices=GRADES, validators=[validators.NoneOf(values='No Grade',message='Please enter appropriate grade')]) markers_grade = SelectField(u'Markers assessment judgement', widget=Select(), choices=GRADES,validators=[validators.optional()]) reported_grade = SelectField(u'Reported assessment judegement', widget=Select(), choices=GRADES,validators=[validators.optional()]) # tic = AllStaffData(u'Teacher in Charge', widget=Select(),validators=[validators.optional()]) discussion = StringField(u'Discussion', widget=TextArea(),validators=[validators.optional()]) finished = BooleanField(u"<p id='finished_p'>", widget=CheckboxInput(),validators=[validators.required(message="The sign off box above must be checked to submit data")])
class ProjectBudgetItemOverallForm(ModelForm): class Meta: model = ProjectBudgetItemOverall sub_category = QuerySelectField( ProjectBudgetSubCategory, query_factory=lambda: ProjectBudgetSubCategory.query.all(), widget=Select())
class LabQualTestRecordForm(ModelForm): class Meta: model = LabQualTestRecord choice = QuerySelectField('Result choices', widget=Select(), allow_blank=False, validators=[Optional()] )
class ProjectRecordForm(ModelForm): class Meta: model = ProjectRecord exclude = ['approved_at', 'created_at', 'updated_at'] parent = QuerySelectField( ParentProjectRecord, query_factory=lambda: ParentProjectRecord.query.all(), allow_blank=True, blank_text='โครงการเดี่ยว', widget=Select()) fund_source = QuerySelectField( ProjectFundSource, query_factory=lambda: ProjectFundSource.query.all(), widget=Select()) contract_upload = FileField('Upload เอกสารสัญญา') final_report_upload = FileField('Upload รายงานฉบับสมบูรณ์')
class ProfileForm(ModelForm): class Meta: model = Profile programs = QuerySelectField('Program', query_factory=lambda: Program.query, widget=Select()) photo_upload = FileField('Photo Upload')
def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) if self.multiple: kwargs["multiple"] = True html = ["<select %s>" % html_params(name=field.name, **kwargs)] for val, label, selected in field.iter_choices(): if callable(val): html.append("<optgroup label='%s'>" % escape(text_type(label))) for child_val, child_label, child_selected in val(): html.append( Select.render_option(child_val, child_label, child_selected)) html.append("</optgroup>") else: html.append(Select.render_option(val, label, selected)) html.append("</select>") return HTMLString("".join(html))
class PostForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) body = TextAreaField('Body', validators=[ DataRequired()], widget=TextArea()) category_id = SelectField('Category', coerce=int, validators=[DataRequired()], widget=Select()) tags = StringField('Tags', validators=[DataRequired()]) submit = SubmitField('Submit')
class ProjectPublicationForm(ModelForm): class Meta: model = ProjectPublication journals = QuerySelectField( ProjectPublicationJournal, query_factory=lambda: ProjectPublicationJournal.query.all(), get_label=lambda x: x.name, widget=Select())
class LabQualTestForm(ModelForm): class Meta: model = LabQualTest choice_set = QuerySelectField('Choice Set', widget=Select(), allow_blank=True, blank_text='ไม่ใช้ชุดคำตอบ', validators=[Optional()] )
class ProjectPublicationAuthorForm(ModelForm): class Meta: model = ProjectPublicationAuthor users = QuerySelectField( User, query_factory=lambda: sorted([u for u in User.query.filter_by(role=2)], key=lambda x: x.fullname_thai), get_label=lambda x: x.profile.fullname_th, widget=Select(), validators=[Optional()])
class OutsideVerificationForm(Form): standard = AllStandardsData('Choose Standard') student = StringField(u'Student Name (Full Name)', widget=TextInput(), validators=[validators.input_required(message=NO_INPUT_ERROR)]) verifier_name = StringField(u'Teacher name (Verifier)', widget=TextInput(), validators=[validators.input_required(message=NO_INPUT_ERROR)]) verifier_school = StringField(u'School of Verifier', widget=TextInput()) verifiers_grade = SelectField(u'Assessment judgement', widget=Select(), choices=GRADES, validators=[validators.NoneOf(values='No Grade',message='Please enter appropriate grade')]) discussion = StringField(u'Discussion', widget=TextArea()) finished = BooleanField(u"<p id='finished_p'>", widget=CheckboxInput(),validators=[validators.required(message="The sign off box above must be checked to submit data")])
class ProjectMemberForm(ModelForm): class Meta: model = ProjectMember users = QuerySelectField( 'User', query_factory=lambda: sorted([u for u in User.query.filter_by(role=2)], key=lambda x: x.fullname_thai), get_label='fullname_thai', allow_blank=True, blank_text='กรุณาเลือกนักวิจัย', widget=Select())
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = True html = ['<select %s>' % html_params(name=field.name, **kwargs)] for val, label, selected in field.iter_choices(): if callable(val): html.append('<optgroup label="%s">' % escape(text_type(label))) for child_val, child_label, child_selected in val(): html.append(Select.render_option(child_val, child_label, child_selected)) html.append('</optgroup>') else: html.append(Select.render_option(val, label, selected)) html.append('</select>') return HTMLString(''.join(html))
class CoveredArea(InsecureForm): name = TextField(_(u'name'), widget=partial(TextInput(), class_='input-medium', placeholder=_(u'Area'))) technologies = SelectMultipleField(_(u'technologies'), choices=TECHNOLOGIES_CHOICES, widget=partial(Select(True), **{'class': 'selectpicker', 'data-title': _(u'Technologies deployed')})) area = GeoJSONField(_('area'), widget=partial(TextArea(), class_='geoinput')) def validate(self, *args, **kwargs): r = super(CoveredArea, self).validate(*args, **kwargs) if bool(self.name.data) != bool(self.technologies.data): self._fields['name'].errors += [_(u'You must fill both fields')] r = False return r
class CompareForm(FlaskForm): """Contact form.""" task_from = SelectMultipleField( "Task from", validators=[ DataRequired(message="Please choose a task to compare from.") ], widget=Select(multiple=False)) task_to = SelectField( "Task to", validators=[ DataRequired(message="Please choose a task to compare to.") ]) submit = SubmitField('Compare tasks')
def __call__(self, field, *args, **kwargs): # 'placeholder' option presence is required for 'allowClear' params = {'placeholder': u''} if self.unescape_html: params['makeHtml'] = True if not field.flags.required: params['allowClear'] = True css_class = kwargs.setdefault('class_', u'') if 'js-widget' not in css_class: css_class += u' js-widget' kwargs['class_'] = css_class kwargs.setdefault('data-init-with', self.js_init) kwargs['data-init-params'] = json.dumps(params) return Select.__call__(self, field, *args, **kwargs)
class WrappedSelect(Select): """Widget to wrap select input in further markup.""" wrapper = '<div>%(field)s</div>' wrapped_widget = Select() def __init__(self, widget=None, wrapper=None, **kwargs): """Initialize wrapped input with widget and wrapper.""" self.wrapped_widget = widget or self.wrapped_widget self.wrapper_args = kwargs if wrapper is not None: self.wrapper = wrapper def __call__(self, field, **kwargs): """Render wrapped input.""" return HTMLString(self.wrapper % dict( field=self.wrapped_widget(field, **kwargs), **self.wrapper_args))
class _SingleChoiceQuerySelectMultipleField(IndicoQuerySelectMultipleField): # single-choice version of the multi select field that uses # a collection instead of a single value for `data` widget = Select() def iter_choices(self): yield ('__None', self.blank_text, self.data is None) yield from super().iter_choices() def process_formdata(self, valuelist): # remove "no value" indicator. QuerySelectMultipleField validation # is broken in WTForms so it never causes a validation error to have # invalid data in valuelist but maybe it gets fixed at some point... valuelist = list(set(valuelist) - {'__None'}) if len(valuelist) > 1: raise ValueError('Received more than one value') super().process_formdata(valuelist)
class PlacementForm(Form): component = HiddenField() name = StringField("Name",[validators.required()], #widget=StaticIfExists(), render_kw={'class':'form-control'}) cls = SelectField("Type", [validators.required()], choices=[(d,d) for d in ('Component','Assembly')], widget=StaticIfExists(Select()), render_kw={'class':'form-control'}) weight = NumericField("Quantity", [validators.required()] , render_kw={'size':1, 'class':'form-control'}) querymod = JSONField("Querymod") #edit = StaticField("Edit", default="link goes here"); #override BaseForm process to restructure placements class _FakePlacement(object): def __init__(self, placement): self.component = (placement.component.id if hasattr(placement.component,'id') else placement.component) self.name = placement.name self.cls = (type(placement.component).__name__ if self.component else None) self.weight = placement.weight self.querymod = placement.querymod def process(self, formdata=None, obj=None, data=None, **kwargs): if isinstance(obj, component.Placement): obj = self._FakePlacement(obj) super().process(formdata=formdata, obj=obj, data=data, **kwargs) #override populate_obj to make new component if necessary def populate_obj(self, obj): comp = self.component.data if not comp or comp == str(None): comp = component.buildcomponentfromdict({ '__class__': self.cls.data, 'name': self.name.data }) obj.component = comp obj.name = self.name.data obj.weight = self.weight.data obj.querymod = self.querymod.data
class Many2manyField(Field): widget = Select(multiple=True) def __init__(self, label, model, validators=None, **kwargs): self.model = model # fixme self.available_records = self.model.query.all() super(Many2manyField, self).__init__(label=label, validators=validators, **kwargs) def iter_choices(self): for record in self.available_records: selected = self.data is not None and record in self.data yield (record, record.name, selected) def _value(self): return list(map(self.model.name_get, self.data)) def process_data(self, value): try: self.data = list(map(self.model.name_get, value)) except (ValueError, TypeError): self.data = None def process_formdata(self, valuelist): self.data = list(map(self.model.name_get, valuelist)) if not all(self.data): raise ValueError( self.gettext( 'Invalid choice(s): one or more data inputs could not be coerced' )) def pre_validate(self, form): if self.data: for d in self.data: if not d: raise ValueError( self.gettext( "'%(value)s' is not a valid choice for this field") % dict(value=d))
class RegisterStep2Form(ModelForm): class Meta: #pylint: disable=no-init,missing-docstring,old-style-class,too-few-public-methods model = User only = ['position', 'organization', 'country'] @classmethod def is_not_empty(cls, user): ''' Returns whether or not the user has filled out any of the fields in the form. Used to determine whether to skip past this form when resuming the registration process. ''' for attr in cls.Meta.only: if getattr(user, attr): return True return False expertise_domain_names = CallableChoicesSelectMultipleField( label=lazy_gettext('Fields of Work'), widget=Select(multiple=True), choices=lambda: [(v, lazy_gettext(v)) for v in current_app.config['DOMAINS']])
def render_option(self, value, label, selected, **kwargs): if self.labelizer: label = self.labelizer(label) return wtfSelect.render_option(value, label, selected, **kwargs)
def render_option(cls, value, label, selected, **kwargs): if value is None: return HTMLString('<option></option>') return Select.render_option(value, label, selected, **kwargs)
def __call__(self, *args, **kwargs): # Just add a select2 css class to the widget and let JQuery do the rest. kwargs = kwargs.copy() kwargs['class'] = 'select2' return Select.__call__(self, *args, **kwargs)