我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用flask_wtf.Form()。
def test_handle_content_type_json_form(self, mocklast, mockcsrf, mockjsonify, mockrender, mockrequest): fake_d = {'Content-Type': 'application/json'} mockrequest.headers.__getitem__.side_effect = fake_d.__getitem__ mockrequest.headers.get.side_effect = fake_d.get mockrequest.headers.__iter__.side_effect = fake_d.__iter__ mockjsonify.side_effect = myjsonify mockcsrf.return_value = "yourcsrf" form = MagicMock(spec=Form, data=dict(foo=1), errors=None) res = util.handle_content_type(dict(template='example.html', form=form)) err_msg = "template key should exist" assert res.get('template') == 'example.html', err_msg err_msg = "jsonify should be called" assert mockjsonify.called, err_msg err_msg = "Form should exist" assert res.get('form'), err_msg err_msg = "Form should have a csrf key/value" assert res.get('form').get('csrf') == 'yourcsrf', err_msg err_msg = "There should be the keys of the form" keys = ['foo', 'errors', 'csrf'] assert res.get('form').keys().sort() == keys.sort(), err_msg
def _generateFormClasses(self, classes): ''' Loops over all ModelClasses and generates a new WTForm class. New form classes are named as [ModelClassName]Form. Sets the new form as an attribute on MarvinForm. Also populates the _param_to_form_lookup dictonary with all ModelClass/WTForm parameters and their corresponding forms. e.g. _param_form_lookup['name'] = marvin.tools.query.forms.IFUDesignForm ''' for key, val in classes.items(): classname = '{0}Form'.format(key) try: newclass = formClassFactory(classname, val, ModelForm) except Exception as e: warnings.warn('class {0} not Formable'.format(key), MarvinUserWarning) else: self.__setattr__(classname, newclass) self._loadParams(newclass)
def jenkins_param_form_factory(form_instance): attributes = {} for field in get_params_data(form_instance): kwargs = \ { 'description': field['description'] , 'default': field['default'] } kwargs.update(field['kwargs']) if field['choices']: kwargs['choices'] = field['choices'] attributes[field['name']] = getattr(fields, field['type'])(**kwargs) def __init__(self, *args, **kwargs): kwargs['csrf_enabled'] = False super(self.__class__, self).__init__(*args, **kwargs) attributes['__init__'] = __init__ return type('Form', (form.Form, ), attributes)
def post_view(slug): q = filter_by_user(Post.query.filter(Post.slug==slug)) post = q.one_or_none() if post is None: return render_page_template( context={"post": None}, template="site/blog/post.html" ) form = Form() if post.enable_comments and current_settings.enable_comments: form = create_comment_form() if form.validate_on_submit(): post.comments.append(Comment(**form.data)) db.session.commit() flash("Your comment was sent") return redirect(url_for('canella-blog.post', slug=post.slug)) return render_page_template( context={"post": post, 'comment_form':form}, template="site/blog/post.html" )
def get_node_form(node_type): """Get a procedurally generated WTForm, based on the dyn_schema and node_schema of a specific node_type. :type node_type: dict :param node_type: Describes the node type via dyn_schema, form_schema and parent """ class ProceduralForm(Form): pass parent_prop = node_type['parent'] ProceduralForm.name = StringField('Name', validators=[DataRequired()]) # Parenting if parent_prop: parent_names = ", ".join(parent_prop) ProceduralForm.parent = HiddenField('Parent ({0})'.format(parent_names)) ProceduralForm.description = TextAreaField('Description') ProceduralForm.picture = FileSelectField('Picture', file_format='image') ProceduralForm.node_type = HiddenField(default=node_type['name']) add_form_properties(ProceduralForm, node_type) return ProceduralForm()
def unique_username(form, field): """ Check if a user already exists with this name :param form: The form which is being passed in :type form: Form :param field: The data value for the 'name' inserted by new User :type field : StringField """ user = User.query.filter(User.name == field.data).first() if user is not None: raise ValidationError('There is already a user with this name')
def valid_password(form, field): """ Function to check for validity of a password :param form: The form which is being passed in :type form: Form :param field: The data value for the 'password' inserted by User :type field : PasswordField """ if len(field.data) == 0: raise ValidationError('new password cannot be empty') if len(field.data) < 10 or len(field.data) > 500: raise ValidationError('Password needs to be between 10 and 500 ' 'characters long (you entered %s characters' % len(field.data))
def role_id_is_valid(form, field): """ Checks for validity of User's Role :param form: The form which is being passed in :type form: Form :param field : The data value for the 'role' inserted by User :type field : SelectField """ role = Role.query.filter(Role.id == field.data).first() if role is None: raise ValidationError('Role id is invalid')
def jenkins_form_factory(*args, **kwargs): attributes = dict\ ( signature = fields.HiddenField\ () , view = fields.SelectField\ ( u'???' , choices=JenkinsViewChoices() , default=None ) , parent = InlineFieldList\ ( InlineFormField ( ParentForm ) , label=u'????????' , description=u'??????? ???????????? ?????' , validators= [ validators.DataRequired() , ] ) , node = fields.SelectField\ ( u'????' , choices=JenkinsNodeChoices() , validators= [ validators.DataRequired() , ] ) , config = fields.StringField\ ( u'???????? ??????' , widget=ReadonlyTextArea() ) ) form_instance = type('Form', (form.Form, ), attributes)(*args, **kwargs) if form_instance.parent.data: attributes['param'] = InlineFormField\ ( jenkins_param_form_factory(form_instance) , u'?????????' ) kwargs['csrf_enabled'] = False return type('Form', (form.Form, ), attributes)(*args, **kwargs)
def __init__(self, *fields, base_form=Form, with_admin=False): class FormWithDynamiclyGeneratedFields(base_form): pass self.raw_form = FormWithDynamiclyGeneratedFields self.raw_fields = self.normalize(fields) self.unbound_fields = list() self.field_map = FIELD_MAP if not with_admin else ADMIN_FIELD_MAP self._generated = False
def __init__(self, *args, **kwargs): WTF.Form.__init__(self, *args, **kwargs) self.subject_id.choices = get_subject_choices() self.role_id.choices = get_role_choices()
def handle_content_type(data): """Return HTML or JSON based on request type.""" from pybossa.model.project import Project if request.headers.get('Content-Type') == 'application/json': message_and_status = last_flashed_message() if message_and_status: data['flash'] = message_and_status[1] data['status'] = message_and_status[0] for item in data.keys(): if isinstance(data[item], Form): data[item] = form_to_json(data[item]) if isinstance(data[item], Pagination): data[item] = data[item].to_json() if (item == 'announcements'): data[item] = [announcement.to_public_json() for announcement in data[item]] if (item == 'blogposts'): data[item] = [blog.to_public_json() for blog in data[item]] if (item == 'categories'): tmp = [] for cat in data[item]: if type(cat) != dict: cat = cat.to_public_json() tmp.append(cat) data[item] = tmp if (item == 'active_cat'): if type(data[item]) != dict: cat = data[item].to_public_json() data[item] = cat if (item == 'users') and type(data[item]) != str: data[item] = [user_to_json(user) for user in data[item]] if (item == 'users' or item =='projects' or item == 'tasks' or item == 'locs') and type(data[item]) == str: data[item] = json.loads(data[item]) if (item == 'found'): data[item] = [user_to_json(user) for user in data[item]] if (item == 'category'): data[item] = data[item].to_public_json() if 'code' in data.keys(): return jsonify(data), data['code'] else: return jsonify(data) else: template = data['template'] del data['template'] if 'code' in data.keys(): error_code = data['code'] del data['code'] return render_template(template, **data), error_code else: return render_template(template, **data)
def validate(self): check_validate = super().validate() if not check_validate: return False sizes_list = self.sizes.data.replace(',', ' ').split() if len(sizes_list) == 0: self.sizes.errors.append('Must have at least one ') return False for elem in sizes_list: try: int(elem) except ValueError: self.sizes.errors.append('Could not parse "%s" as int' % elem) return False return True # class UploadImages(Form): # # # upload = SubmitField('Upload') # from mothership.models import User # # # class LoginForm(Form): # username = StringField(u'Username', validators=[validators.required()]) # password = PasswordField(u'Password', validators=[validators.optional()]) # # def validate(self): # check_validate = super(LoginForm, self).validate() # # # if our validators do not pass # if not check_validate: # return False # # # Does our the exist # user = User.query.filter_by(username=self.username.data).first() # if not user: # self.username.errors.append('Invalid username or password') # return False # # # Do the passwords match # if not user.check_password(self.password.data): # self.username.errors.append('Invalid username or password') # return False # # return True