class FragmentForm(Form): """ A fragment form is like a content form but without a summary or template. """ previous_id = wtf.HiddenField(u"Previous revision") title = wtf.TextField(u"Title", validators=[wtf.Required()]) name = wtf.TextField(u"URL name", validators=[wtf.Required(), valid_name]) content = RichTextField(u"Page content", linkify=False, tinymce_options=tinymce_options, sanitize_tags=richtext_sanitize_tags, sanitize_attributes=richtext_sanitize_attributes) properties = DictField(u"Properties") def validate_previous_id(self, field): if not field.data: field.data = None else: try: field.data = int(field.data) except ValueError: raise wtf.ValidationError(u"Unknown previous revision") def validate_name(self, field): # TODO pass
class UserRegisterForm(wtf.Form): username = wtf.TextField( 'Username', validators=[ wtf.Required(), wtf.Length(min=2, max=50), wtf.Regexp( '^[a-zA-Z0-9_]*$', message= ('Username must only contain a to z, 0 to 9, and underscores.' )) ], description=( 'Your username is public and used as part of your project name.')) email = wtf.TextField('Email', validators=[wtf.Required(), wtf.validators.Email()]) password = wtf.PasswordField('Password', validators=[ wtf.Required(), wtf.Length(5), wtf.EqualTo('confirm', 'Passwords do not match.'), ]) confirm = wtf.PasswordField('Confirm Password') def validate_username(form, field): from notifico.views.account import _reserved username = field.data.strip().lower() if username in _reserved or User.username_exists(username): raise wtf.ValidationError('Sorry, but that username is taken.')
class ResourceActionForm(Form): """ Edit an action associated with a resource """ name = wtf.TextField( 'Action name', validators=[wtf.Required()], description="Name of the action as a single word in lower case. " "This is provided by applications as part of the scope in the form " "'resource/action' when requesting access to a user's resources. " "Read actions are implicit when applications request just 'resource' " "in the scope and do not need to be specified as an explicit action.") title = wtf.TextField( 'Title', validators=[wtf.Required()], description='Action title that is displayed to users') description = wtf.TextAreaField( 'Description', description='An optional description of what the action is') def validate_name(self, field): if not valid_username(field.data): raise wtf.ValidationError("Name contains invalid characters.") existing = ResourceAction.query.filter_by( name=field.data, resource=self.edit_resource).first() if existing and existing.id != self.edit_id: raise wtf.ValidationError( "An action with that name already exists for this resource")
class RegisterForm(Form): fullname = wtf.TextField('Full name', validators=[wtf.Required()]) email = wtf.html5.EmailField('Email address', validators=[wtf.Required(), wtf.Email()]) username = wtf.TextField('Username (optional)', validators=[wtf.Optional()]) password = wtf.PasswordField('Password', validators=[wtf.Required()]) confirm_password = wtf.PasswordField( 'Confirm password', validators=[wtf.Required(), wtf.EqualTo('password')]) recaptcha = wtf.RecaptchaField( 'Are you human?', description="Type both words into the text box") def validate_username(self, field): if field.data in RESERVED_USERNAMES: raise wtf.ValidationError, "That name is reserved" if not valid_username(field.data): raise wtf.ValidationError( u"Invalid characters in name. Names must be made of ‘a-z’, ‘0-9’ and ‘-’, without trailing dashes" ) existing = User.query.filter_by(username=field.data).first() if existing is not None: raise wtf.ValidationError("That username is taken") def validate_email(self, field): existing = UserEmail.query.filter_by(email=field.data).first() if existing is not None: raise wtf.ValidationError( Markup( 'This email address is already registered. Do you want to <a href="%s">login</a> instead?' % url_for('login')))
class RegisterForm(wtf.Form): email = wtf.TextField( 'E-mail', validators=[wtf.validators.Required(), wtf.validators.Email()]) first_name = wtf.TextField('First Name', validators=[wtf.validators.Required()]) last_name = wtf.TextField('Last Name', validators=[wtf.validators.Required()]) phone_number = wtf.TextField('Phone Number') organisation = wtf.TextField('Organisation') def validate_email(self, field): if User.objects.filter(email=field.data, invitee__exists=False, country__exists=True).count() > 0: raise wtf.ValidationError( 'User is already invited as country coordinator with Eionet Account' ) def save(self, user_invitee): defaults = self.data defaults['id'] = slugify( '%s %s' % (self.data['first_name'], self.data['last_name'])) defaults['invitee'] = user_invitee defaults['country'] = user_invitee.country user, created = User.objects.get_or_create(email=self.data['email'], defaults=defaults) return user
class CustomerForm(wtf.Form): address = wtf.TextField(u'收获地址', validators=[wtf.required()]) phone = wtf.TextField(u'联系电话', validators=[wtf.required()]) def validate_login(self, field): if not login.current_user.is_authenticated(): raise wtf.ValidationError('Not login')
class SignUpForm(Form): """Sign up form.""" name = wtf.TextField('Name', validators=[ wtf.Required(), wtf.Length(max=100), ], description='e.g. Johnny') primary_email = wtf.TextField('E-mail', validators=[ wtf.Required(), wtf.Email(), wtf.Length(max=100), ]) password = wtf.PasswordField('Password', validators=[ wtf.Required(), ]) password_check = wtf.PasswordField('Password once more', validators=[ wtf.EqualTo( 'password', message='Passwords must match'), ], description='protection against typos')
class ParticipantForm(Form): skill_levels = [('Beginner', 'Beginner'), ('Intermediate', 'Intermediate'), ('Advanced', 'Advanced')] reason_to_join = RichTextField( "Reason To Join", description="Why would you love to join Hacknight", validators=[wtf.Required()], content_css="/static/css/editor.css") phone_no = wtf.TextField( "Telephone No", description="Telephone No", validators=[wtf.Required(), wtf.validators.length(max=15)]) email = wtf.html5.EmailField( "Email", description="Email Address, We will never spam you .", validators=[wtf.Required(), wtf.validators.length(max=80)]) job_title = wtf.TextField( "Job Title", description="What is your job title? E.G: Senior Software " "Engineer at Awesome company", validators=[wtf.Required(), wtf.validators.length(max=120)]) company = wtf.TextField( "Company", description="Company Name", validators=[wtf.Optional(), wtf.validators.length(max=1200)]) skill_level = wtf.RadioField("Skill Level", description="What is your skill level?", choices=skill_levels)
class ProfileForm(wtf.Form): nickname = wtf.TextField('nickname', validators=[wtf.Required(message=u'请填写昵称')]) slug = wtf.TextField( 'slug', validators=[ wtf.Regexp(regex=r'^([a-zA-Z][a-zA-Z0-9_-]{4,23})?$', message=u'长度应为5~24位,仅能包含数字、英文字母及下划线(_)和减号(-),并且需要以字母开头') ]) phone = wtf.TextField( 'phone', validators=[wtf.Regexp(regex=r'^(1\d{10})?$', message=u'请输入有效的手机号码')]) phone_status = wtf.RadioField('phone_status', choices=[('0', u'不公开'), ('1', u'公开'), ('2', u'仅向会员公开')], default='0') # photo = db.Column(db.String(255), nullable=True) # 存一张照片,既然有线下的聚会的,总得认得人才行 motoo = wtf.TextAreaField( 'motoo', validators=[wtf.Length(min=0, max=255, message=u'座右铭最多为255个字符')]) introduction = wtf.TextAreaField( 'introduction', validators=[wtf.Length(min=0, max=3000, message=u'个人介绍最多为3000个字')]) def __init__(self, *args, **kargs): wtf.Form.__init__(self, *args, **kargs) self.user = None
class UserGroupForm(wtf.Form): name = wtf.TextField('URL name', validators=[wtf.Required()]) title = wtf.TextField('Title', validators=[wtf.Required()]) users = wtf.TextAreaField( 'Users', validators=[wtf.Required()], description="Usernames or email addresses, one per line")
class InventoryItemForm(wtf.Form): """Represents the admin inventory item form""" group = wtf.SelectField() name = wtf.TextField(validators=[wtf.required()]) identifier = wtf.TextField() status = wtf.SelectField(choices=INVENTORY_STATUS, coerce=int) comment = wtf.TextAreaField() def __init__(self, formdata=None, obj=None, prefix='', **kwargs): super(InventoryItemForm, self).__init__(request.form, obj, prefix, **kwargs) self.csrf_enabled = False self.group.choices = [(str(grp.id), grp.name) for grp in InventoryGroup.objects] # select the group if request.args.get('id') and not self.is_submitted(): item = InventoryItem.objects(id=request.args.get('id')).get() self.group.data = str(item.group.id) def validate(self, extra_validators=None): success = True # run validation for fields for field in (self.name, self.status): if not field.validate(self.data): success = False self.errors[field.name] = field.errors return success def process(self, formdata=None, obj=None, **kwargs): super(InventoryItemForm, self).process(formdata, obj, **kwargs) if self.is_submitted(): # convert to admin model friendly types self.status.data = int(self.status.data)
class ContentForm(Form): previous_id = wtf.HiddenField(u"Previous revision") title = wtf.TextField(u"Title", validators=[wtf.Required()]) name = wtf.TextField(u"URL name", validators=[wtf.Optional(), valid_name]) description = wtf.TextAreaField(u"Summary", description=u"Summary of this page") content = RichTextField(u"Page content", linkify=False, buttons1=richtext_buttons1, valid_elements=richtext_valid_elements, sanitize_tags=richtext_sanitize_tags, sanitize_attributes=richtext_sanitize_attributes) template = wtf.TextField( "Template", validators=[wtf.Required()], default='page.html', description=u"Template with which this page will be rendered.") properties = DictField(u"Properties") def validate_previous_id(self, field): if not field.data: field.data = None else: try: field.data = int(field.data) except ValueError: raise wtf.ValidationError("Unknown previous revision") def validate_name(self, field): # TODO pass
class RegistrationForm(wtf.Form): login = wtf.TextField(u'用户名', validators=[wtf.required()]) email = wtf.TextField(u'邮箱') password = wtf.PasswordField(u'密码', validators=[wtf.required()]) def validate_login(self, field): if db.session.query(User).filter_by(login=self.login.data).count() > 0: raise wtf.ValidationError('Duplicate username')
class RegistrationForm(wtf.Form): login = wtf.TextField(validators=[wtf.required()]) email = wtf.TextField() password = wtf.PasswordField(validators=[wtf.required()]) def validate_login(self, field): if User.objects(login=self.login.data): raise wtf.ValidationError('Duplicate username')
class RegistrationForm(wtf.Form): login = wtf.TextField(validators=[wtf.required()]) email = wtf.TextField(validators=[wtf.required(), wtf.validators.Email()]) password = wtf.PasswordField(validators=[wtf.required()]) def validate_login(self, field): current_ident_hash = bcrypt.generate_password_hash("".join(self.login.raw_data)) if User.filter(ident_hash=current_ident_hash).count(): raise wtf.ValidationError(u'Користувач з ніком %s вже зареєстрований. Оберіть інше ім`я')
class RedirectForm(Form): name = wtf.TextField(u"URL name", validators=[wtf.Optional(), valid_name]) title = wtf.TextField(u"Title", validators=[wtf.Required()]) redirect_url = wtf.TextField(u"Redirect URL", validators=[wtf.Required()]) properties = DictField(u"Properties") def validate_name(self, field): # TODO pass
class MapForm(Form): name = wtf.TextField(u"URL name", validators=[wtf.Required(), valid_name]) title = wtf.TextField(u"Title", validators=[wtf.Required()]) list = wtf.TextAreaField( 'Map markers', validators=[wtf.Required()], description=u'Enter each row as a JSON object with name, title, url, ' u'latitude, longitude, zoomlevel and marker. ' u'The URL, zoomlevel and marker can be null, others cannot.') properties = DictField(u"Properties")
class UserForm(wtf.Form): name = wtf.TextField('Name') email = wtf.TextField('Email') password = wtf.TextField('Password') # Inner form inner = fields.InlineFormField(InnerForm) # Form list form_list = fields.InlineFieldList(fields.InlineFormField(InnerForm))
class ProjectForm(Form): title = wtf.TextField("Title", description="Title of the project", validators=[wtf.Required("A title is required"), wtf.validators.length(max=250)]) blurb = wtf.TextField("Blurb", description="A single-line summary of the project", validators=[wtf.Required("A blurb is required"), wtf.validators.length(max=250)]) description = RichTextField(u"Description", description="Detailed description of your project", content_css="/static/css/editor.css") participating = wtf.RadioField("Will you be participating?", default=1, coerce=getbool, choices=[(1, u"I will be working on this project"), (0, u"I’m proposing an idea for others to take up")])
class ElectionForm(wtf.Form): summary = wtf.TextField( 'Summary', [wtf.validators.Required(), wtf.validators.Length(max=150)]) alias = wtf.TextField('Alias', [ wtf.validators.Required(), wtf.validators.Length(max=100), wtf.validators.Regexp('[a-z0-9_-]+', message=('Alias may only contain lower case ' 'letters, numbers, hyphens and ' 'underscores.')), ]) description = wtf.TextAreaField('Description', [wtf.validators.Required()]) url = wtf.TextField('URL', [ wtf.validators.Required(), wtf.validators.URL(), wtf.validators.Length(max=250) ]) start_date = wtf.DateField('Start date', [wtf.validators.Required()]) end_date = wtf.DateField('End date', [wtf.validators.Required()]) number_elected = wtf.IntegerField( 'Number elected', [wtf.validators.Required(), wtf.validators.NumberRange(min=1)], default=1) candidates_are_fasusers = wtf.BooleanField('Candidates are FAS users?') frontpage = wtf.BooleanField('Show on front page?') embargoed = wtf.BooleanField('Embargo results?', default=True) def __init__(form, election_id=None, *args, **kwargs): super(ElectionForm, form).__init__(*args, **kwargs) form._election_id = election_id def validate_summary(form, field): check = Election.query.filter_by(summary=form.summary.data).all() if check: if not (form._election_id and form._election_id == check[0].id): raise wtf.ValidationError('There is already another election ' 'with this summary.') def validate_alias(form, field): if form.alias.data == 'new': raise wtf.ValidationError( flask.Markup('The alias cannot be ' '<code>new</code>.')) check = Election.query.filter_by(alias=form.alias.data).all() if check: if not (form._election_id and form._election_id == check[0].id): raise wtf.ValidationError('There is already another election ' 'with this alias.') def validate_end_date(form, field): if form.end_date.data <= form.start_date.data: raise wtf.ValidationError('End date must be later than ' 'start date.')
class ListForm(Form): name = wtf.TextField(u"URL name", validators=[wtf.Required(), valid_name]) title = wtf.TextField(u"Title", validators=[wtf.Required()]) list = wtf.TextAreaField( 'Items', validators=[wtf.Required()], description= u'Enter each row as a JSON array with ["name", title", "url", "folder/node"]. ' u'For nodes in the root folder, use "/node". To not include a node, use "".' ) properties = DictField(u"Properties")
class ActivityForm(RedirectForm): title = wtf.TextField(u'活动标题', validators=[ \ wtf.Required(message=u'请为活动填写一个标题')]) content = wtf.TextAreaField(u'活动简介', validators=[ \ wtf.Length(min=10, max=5000, message=u'简介至少10个字')]) start_time = wtf.TextField(u'开始时间', validators=[ \ wtf.Required(message=u'需要指定开始时间')]) end_time = wtf.TextField(u'结束时间', validators=[ \ wtf.Required(message=u'需要指定结束时间')]) address = wtf.TextField(u'活动地点') latitude = wtf.HiddenField() longitude = wtf.HiddenField()
class SubscribeForm(BaseContactsForm): """ Subscribe form. """ phone = wtf.TextField(_('Phone'), validators=[Required()]) skype = wtf.TextField(_('Skype'), validators=[Required()]) flow = wtf.SelectField(_('Flow'), choices=FLOW_CHOICES, validators=[Required()]) comments = wtf.TextField(_('Additional comments'), widget=wtf.TextArea()) template = 'mails/subscribe.txt' title = _('Flow subscription')
class FolderForm(Form): name = wtf.TextField( u"URL name", validators=[wtf.Optional(), valid_name], description=u"Folder name as it appears in the URL (without slashes)") title = wtf.TextField( u"Title", description=u"Folder title, used in the per-folder blog feed") theme = wtf.SelectField(u"Theme") def validate_name(self, field): # TODO pass
class EventForm(ContentForm): start_datetime = DateTimeField(u"Start date/time", validators=[wtf.Required()]) end_datetime = DateTimeField(u"End date/time", validators=[wtf.Required()]) timezone = wtf.SelectField(u"Timezone", choices=timezone_list, validators=[wtf.Required()]) location_name = wtf.TextField(u"Location name", validators=[wtf.Required()]) location_address = wtf.TextField(u"Address", validators=[wtf.Required()]) map = wtf.QuerySelectField(u"Map", get_label='title', allow_blank=True) mapmarker = wtf.TextField(u"Map marker") capacity = wtf.IntegerField(u"Capacity", validators=[wtf.Required()]) allow_waitlisting = wtf.BooleanField(u"Allow wait-listing if over capacity", default=False) allow_maybe = wtf.BooleanField(u"Allow “Maybe” responses", default=True) participant_list = wtf.QuerySelectField(u"Participant list", get_label='title', allow_blank=True) properties = DictField(u"Properties")
class EventForm(Form): title = wtf.TextField( "Title", description="Name of the Event", validators=[wtf.Required(), wtf.NoneOf(values=["new"])]) name = wtf.TextField( "URL name", validators=[ wtf.Optional(), ValidName(), AvailableName(u"There’s another event with the same name") ], description="URL identifier, leave blank to autogenerate") blurb = wtf.TextField( "Blurb", description="Single line blurb introducing the event") description = RichTextField( "Description", description="Detailed description of the event", content_css="/static/css/editor.css") venue = wtf.QuerySelectField( "Venue", description=Markup( 'Venue for this event (<a href="/venue/new">make new</a>)'), query_factory=lambda: Venue.query, get_label='title', ) start_datetime = DateTimeField( "Start date/time", description="The date and time at which this event begins", validators=[wtf.Required()]) end_datetime = DateTimeField( "End date/time", description="The date and time at which this event ends", validators=[wtf.Required()]) ticket_price = wtf.TextField( "Ticket price", description="Entry fee, if any, to be paid at the venue") total_participants = wtf.IntegerField( "Venue capacity", description= "The number of people this venue can accommodate. Registrations will be closed after that. Use 0 to indicate unlimited capacity", default=50, validators=[wtf.Required()]) website = wtf.TextField("Website", description="Related Website (Optional)", validators=[wtf.Optional()]) def validate_end_datetime(self, field): if field.data < self.start_datetime.data: raise wtf.ValidationError( u"Your event can’t end before it starts.")
class SignupForm(wtf.Form): email = wtf.TextField('email', validators=[ wtf.Required(message=u'请填写电子邮件'), wtf.Email(message=u'无效的电子邮件') ]) nickname = wtf.TextField('nickname', validators=[ wtf.Required(message=u'请填写昵称'), wtf.Length(min=2, max=20, message=u'昵称应为2到20字符') ]) password = wtf.PasswordField('password', validators=[ wtf.Required(message=u'请填写密码'), wtf.Length(min=5, max=20, message=u'密码应为5到20位字符') ]) repassword = wtf.PasswordField('repassword', validators=[ wtf.Required(message=u'请填写确认密码'), wtf.EqualTo('password', message=u'两次输入的密码不一致') ]) next = wtf.HiddenField('next') def __init__(self, *args, **kargs): wtf.Form.__init__(self, *args, **kargs) self.user = None def validate(self): wtf.Form.validate(self) # 验证邮箱是否注册 if not self.email.errors: user = get_user(email=self.email.data) user and self.email.errors.append(u'该邮箱已被注册') self.user = User(email=self.email.data, nickname=self.nickname.data, openids=[ UserOpenID(provider=session['openid_provider'], openid=session['current_openid']) ]) self.user.set_password(self.password.data) self.user.info = UserInfo() return len(self.errors) == 0
class EventForm(Form): """Form to create or edit an event.""" name = wtf.TextField('Name', validators=[ wtf.Required(), wtf.Length(max=200), ]) starts_at = wtf.DateTimeField('When', format='%Y-%m-%d %H:%M') venue = wtf.TextField('Where', validators=[ wtf.Length(max=200), ]) description = wtf.TextAreaField('What') contacts_invited_ids_str = wtf.HiddenField()
class ProfileNewForm(ProfileFormBase, Form): fullname = wtf.TextField('Full name', validators=[wtf.Required()]) email = wtf.html5.EmailField('Email address', validators=[wtf.Required(), wtf.Email()]) username = wtf.TextField('Username (optional)') description = wtf.TextAreaField('Bio') def validate_email(self, field): existing = UserEmail.query.filter_by(email=field.data).first() self.existing_email = existing # Save for later if existing is not None and existing.user != self.edit_obj: raise wtf.ValidationError( "This email address has been claimed by another user.")
class DataForm(Form): name = wtf.TextField(u"URL name", validators=[wtf.Required(), valid_name]) title = wtf.TextField(u"Title", validators=[wtf.Required()]) data = wtf.TextAreaField(u"Data", validators=[wtf.Required()], description=u"Enter JSON data") properties = DictField(u"Properties") def validate_data(self, field): # Check for exceptions when loading data parsed = simplejson.loads(field.data, use_decimal=True) if not isinstance(parsed, dict): raise wtf.ValidationError( u'This is not a valid JSON object. Use {"key": value, ...}')