Python flask_wtf.Form() Examples

The following are 11 code examples of flask_wtf.Form(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_wtf , or try the search function .
Example #1
Source File: __init__.py    From pylint-flask with GNU General Public License v2.0 6 votes vote down vote up
def transform_flask_from_long(node):
    '''Translates a flask.ext.wtf from-style import into a non-magical import.

    Translates:
        from flask.ext.wtf import Form
        from flask.ext.admin.model import InlineFormAdmin
    Into:
        from flask_wtf import Form
        from flask_admin.model import InlineFormAdmin

    '''
    actual_module_name = make_non_magical_flask_import(node.modname)
    new_node = nodes.ImportFrom(actual_module_name, node.names, node.level)
    copy_node_info(node, new_node)
    mark_transformed(new_node)
    return new_node 
Example #2
Source File: forms.py    From marvin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        ''' Initializes a Marvin Form

        Generates all the WTForms from the SQLAlchemy ModelClasses defined in the MaNGA DB.

        _param_form_lookup = dictionary of all modelclass parameters
        of form {'SQLalchemy ModelClass parameter name': WTForm Class}
        '''

        self._release = kwargs.get('release', config.release)
        self.verbose = kwargs.get('verbose', False)
        if marvindb:
            self._modelclasses = FuzzyDict(marvindb.buildUberClassDict(release=self._release))
            self._param_form_lookup = ParamFormLookupDict(**kwargs)
            self._param_fxn_lookup = ParamFxnLookupDict()
            self._paramtree = tree()
            self._generateFormClasses(self._modelclasses)
            self._generateFxns()
            self.SearchForm = SearchForm
            self._cleanParams(**kwargs) 
Example #3
Source File: forms.py    From marvin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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:
                if self.verbose:
                    warnings.warn('class {0} not Formable'.format(key), MarvinUserWarning)
            else:
                self.__setattr__(classname, newclass)
                self._loadParams(newclass) 
Example #4
Source File: __init__.py    From pylint-flask with GNU General Public License v2.0 5 votes vote down vote up
def is_flask_from_import_long(node):
    '''Check if an import is like `from flask.ext.wtf import Form`.'''
    # Check for transformation first so we don't double process
    return not is_transformed(node) and node.modname.startswith('flask.ext.') 
Example #5
Source File: testauth.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def form(self):
        class TestLoginForm(Form):
            username = StringField(u'Username', validators=[InputRequired()])
            password = PasswordField(u'Password', validators=[InputRequired()])
            submit = SubmitField(u'Log In using {}'.format(self.name))
        return TestLoginForm 
Example #6
Source File: __init__.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def form(self):
        """Return a :py:class:`flask_wtf.Form` subclass to login with."""
        class AuthForm(Form):
            submit = SubmitField(gettext(
                    u'Log In using %(authmethod_name)s',
                    authmethod_name=self.name))
        return AuthForm 
Example #7
Source File: evesso.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def form(self):
        class EveSSOForm(Form):
            submit = ImageField(src=static_file('evesso.png'),
                    alt=u"Log in with EVE Online")

        return EveSSOForm 
Example #8
Source File: forms.py    From marvin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def formClassFactory(name, model, baseclass):
    ''' Generates a new WTForm Class based on SQLalchemy Model Class.

    Subclasses a base WTF Form class that also contains the SQLAlchemy
    Model Class information inside it.

    Each class contains as attributes:
        Meta = a class called Meta.  Meta.model contains the SQLalchemy ModelClass
        data = a dictionary of parameters: form input that gets mapped to the sqlalchemy parameter
        errors = a dictionary of errors returned by invalid form validation
        validate = a method to validate all elements in this form
        parameter_X = a WTForm Field mapped to respective sqlalchemy table column

        e.g.
        The ModelClass IFUDesign mapped to mangadatadb.ifu_design sql table gets transformed into
        WTForm IFUDesignForm, with IFUDesignForm.Meta.model = marvin.db.models.DataModelClasses.IFUDesign

    Parameters:
        name (str):
            The name of the Form Class
        mdoel (class):
            The SQLAlchemy Model Class
        baseclass (class):
            The base class to sub class from

    Returns:
        the new WTF form subclass
    '''

    Meta = type('Meta', (object,), {'model': model})
    newclass = type(name, (baseclass,), {'Meta': Meta})
    return newclass

# build a wtform select field for operators; tested but no longer used
# can't seem to attach operator field to every individual parameter 
Example #9
Source File: forms.py    From marvin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        nforms = len([f for f in self.__dict__.keys() if 'Form' in f])
        return ('<MarvinForm (release={0._release}, n_parameters={1}, n_functions={2}, '
                'n_forms={3})>'.format(self, len(self._param_form_lookup), len(self._param_fxn_lookup), nforms)) 
Example #10
Source File: views.py    From penn-club-ratings with MIT License 5 votes vote down vote up
def submit_review(club_id):
    class F(Form):
        pass

    for field in Question.query.all():
        if field.type == 'Rating':
            setattr(F, '{}_q'.format(field.id),
                    SelectField(
                        '{}. Pick from {} to {}'.format(field.content, 1,
                                                        5),
                        description=field.description,
                        choices=[('{}'.format(x + 1), x + 1)
                                 for x in range(5)]))
        elif field.type == 'Numerical':
            setattr(F, '{}_q'.format(field.id),
                    DecimalField(
                        '{}'.format(field.content),
                        description=field.description))
        if field.free_response:
            setattr(F, '{}_resp'.format(field.id),
                    TextAreaField('Please feel free to elaborate'))
    setattr(F, 'submit', SubmitField('Submit Rating'))
    form = F()
    if form.validate_on_submit():
        for x in form:
            if x.name.find('_q') > -1:
                if (x.name.find('_q')):
                    q_id = x.name.split('_')[0]
                    answer = form['{}_resp'.format(
                        q_id)].data if '{}_resp'.format(q_id) in form else ''
                    rating = x.data
                Answer.newAnswer(answer, rating, current_user.id, q_id,
                                 club_id)

        flash('Club Review successfully added', 'form-success')
    return render_template('main/submit-review.html', form=form) 
Example #11
Source File: forms.py    From puffin with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self):
        rv = flask_wtf.Form.validate(self)
        if not rv:
            return False

        if self.domain.data:
            server_name = app.config["SERVER_NAME_FULL"]
            if (server_name != "localhost"
                    and not self.domain.data.endswith(current_user.login + "." + server_name)
                    and self.domain.data.endswith(server_name)):
                self.domain.errors.append('Invalid domain, cannot end with ' + server_name)
                return False

        return True