예제 #1
0
 def getForm( prodid ):
     f = model_form( Articolo, exclude = ( 'thumb' ) ) 
     if prodid is None:
         return f()
     articolo = Articolo.getArticoloById( prodid )
     form = f( None, articolo )
     return form
예제 #2
0
class OrganizationForm(
        model_form(Organization,
                   exclude=[
                       'incidents', 'is_admin', 'timestamp_signup',
                       'timestamp_login', 'permissions'
                   ]), OrganizationValidatorsMixIn):
    """ All fields available to all levels of admin. """

    incidents = MultiCheckboxField(
        choices=[(event.key(), event.name) for event in event_db.Event.all()],
        coerce=event_key_coerce,
    )

    permissions = SelectField(u'Permission',
                              choices=[('Full Access', 'Full Access'),
                                       ('Partial Access', 'Partial Access'),
                                       ('Situational Awareness',
                                        'Situational Awareness')])
    timestamp_login = DateTimeField("Last logged in", [validators.optional()])

    timestamp_login = DateTimeField("Last logged in", [validators.optional()])
    activate_by = DateTimeField("Activate By", [validators.optional()])
    activated_at = DateTimeField("Activated At", [validators.optional()])

    def __init__(self, *args, **kwargs):
        super(OrganizationForm, self).__init__(*args, **kwargs)

        # override incidents data
        incidents = kwargs.get('incidents')
        if incidents is not None:
            self.incidents.data = incidents
class ContactForm(model_form(Contact, exclude=['organization'])):

    id = HiddenField()
    first_name = TextField('First Name', [
        validators.Length(min=1,
                          max=100,
                          message="Name must be between 1 and 100 characters")
    ])
    last_name = TextField('Last Name', [
        validators.Length(min=1,
                          max=100,
                          message="Name must be between 1 and 100 characters")
    ])
    title = TextField('Org Title', [
        validators.Length(
            min=1,
            max=100,
            message="Org Title must be between 1 and 100 characters")
    ])
    phone = TextField('Phone', [
        validators.Length(
            min=1, max=15, message="Phone must be between 1 and 15 characters")
    ])
    email = TextField('Email', [
        validators.Length(
            min=1,
            max=100,
            message="Email must be between 1 and 100 characters"),
        validators.Email(message="That's not a valid email address.")
    ])
예제 #4
0
    def test_not_implemented_properties(self):
        # This should not raise NotImplementedError.
        form_class = model_form(AllPropertiesModel)

        # These should be set.
        self.assertEqual(hasattr(form_class, 'prop_string'), True)
        self.assertEqual(hasattr(form_class, 'prop_byte_string'), True)
        self.assertEqual(hasattr(form_class, 'prop_boolean'), True)
        self.assertEqual(hasattr(form_class, 'prop_integer'), True)
        self.assertEqual(hasattr(form_class, 'prop_float'), True)
        self.assertEqual(hasattr(form_class, 'prop_date_time'), True)
        self.assertEqual(hasattr(form_class, 'prop_date'), True)
        self.assertEqual(hasattr(form_class, 'prop_time'), True)
        self.assertEqual(hasattr(form_class, 'prop_string_list'), True)
        self.assertEqual(hasattr(form_class, 'prop_reference'), True)
        self.assertEqual(hasattr(form_class, 'prop_self_refeference'), True)
        self.assertEqual(hasattr(form_class, 'prop_blob'), True)
        self.assertEqual(hasattr(form_class, 'prop_text'), True)
        self.assertEqual(hasattr(form_class, 'prop_category'), True)
        self.assertEqual(hasattr(form_class, 'prop_link'), True)
        self.assertEqual(hasattr(form_class, 'prop_email'), True)
        self.assertEqual(hasattr(form_class, 'prop_geo_pt'), True)
        self.assertEqual(hasattr(form_class, 'prop_phone_number'), True)
        self.assertEqual(hasattr(form_class, 'prop_postal_address'), True)
        self.assertEqual(hasattr(form_class, 'prop_rating'), True)

        # These should NOT be set.
        self.assertEqual(hasattr(form_class, 'prop_list'), False)
        self.assertEqual(hasattr(form_class, 'prop_user'), False)
        self.assertEqual(hasattr(form_class, 'prop_im'), False)
예제 #5
0
class BadgeHandler(BadgeItemHandler):
    KIND = Badge
    FORM = model_form(Badge)

    get_actions = BadgeItemHandler.get_actions + ['criteria']

    def htmlize_fields(self, fields):
        fields['image'] = Markup('<img src="%s" alt="%s">') % (fields['image'],
                                                               fields['image'])
        fields['criteria'] = Markup('<a href="%(url)s">criteria page</a>') % {
            'url': fields['criteria'],
        }
        fields['evidence_page_criteria'] = Markup(
            fields['evidence_page_criteria'])
        return super(BadgeHandler, self).htmlize_fields(fields)

    def to_dict(self, obj):
        d = super(BadgeHandler, self).to_dict(obj)
        d['criteria'] = self.request.host_url + self._action_url(
            action='criteria')
        d['image'] = urlparse.urljoin(self.request.host_url, d['image'])
        return d

    def get_criteria(self):
        obj = self._get_object_or_abort()
        self.template_value['navbar'] = {}
        self.template_value['badge'] = obj
        self.render('badge_criteria.html')
예제 #6
0
class AssertionHandler(BadgeItemHandler):
    KIND = BadgeAssertion
    FORM = model_form(BadgeAssertion)

    def _get_object_or_abort(self, create=False):
        if 'name' not in self.request.GET:
            self.abort(400)

        try:
            key_id = int(self.request.GET.get('name', -1))
        except ValueError:
            self.abort(400, "Your assertion ID must be an integer")
        logging.info('key_id is %d', key_id)
        obj = self.KIND.get_by_id(key_id)
        if not obj:
            if not create:
                self.abort(404)
            else:  # yes create
                obj = self.KIND()
        return obj

    def to_dict(self, obj):
        d = super(AssertionHandler, self).to_dict(obj)
        d['uid'] = obj.uid
        d['verify'] = {
            'type': 'hosted',
            'url': self.request.host_url + self._action_url('json'),
        }
        return d
예제 #7
0
파일: tests.py 프로젝트: sskrab001/dpxdt
    def test_field_attributes(self):
        form_class = model_form(
            Author,
            field_args={
                'name': {
                    'label': 'Full name',
                    'description': 'Your name',
                },
                'age': {
                    'label': 'Age',
                    'validators': [validators.NumberRange(min=14, max=99)],
                },
                'city': {
                    'label':
                    'City',
                    'description':
                    'The city in which you live, not the one in which you were born.',
                },
                'is_admin': {
                    'label': 'Administrative rights',
                },
            })
        form = form_class()

        self.assertEqual(form.name.label.text, 'Full name')
        self.assertEqual(form.name.description, 'Your name')

        self.assertEqual(form.age.label.text, 'Age')

        self.assertEqual(form.city.label.text, 'City')
        self.assertEqual(
            form.city.description,
            'The city in which you live, not the one in which you were born.')

        self.assertEqual(form.is_admin.label.text, 'Administrative rights')
예제 #8
0
파일: tests.py 프로젝트: sskrab001/dpxdt
    def test_not_implemented_properties(self):
        # This should not raise NotImplementedError.
        form_class = model_form(AllPropertiesModel)

        # These should be set.
        self.assertEqual(hasattr(form_class, 'prop_string'), True)
        self.assertEqual(hasattr(form_class, 'prop_byte_string'), True)
        self.assertEqual(hasattr(form_class, 'prop_boolean'), True)
        self.assertEqual(hasattr(form_class, 'prop_integer'), True)
        self.assertEqual(hasattr(form_class, 'prop_float'), True)
        self.assertEqual(hasattr(form_class, 'prop_date_time'), True)
        self.assertEqual(hasattr(form_class, 'prop_date'), True)
        self.assertEqual(hasattr(form_class, 'prop_time'), True)
        self.assertEqual(hasattr(form_class, 'prop_string_list'), True)
        self.assertEqual(hasattr(form_class, 'prop_reference'), True)
        self.assertEqual(hasattr(form_class, 'prop_self_refeference'), True)
        self.assertEqual(hasattr(form_class, 'prop_blob'), True)
        self.assertEqual(hasattr(form_class, 'prop_text'), True)
        self.assertEqual(hasattr(form_class, 'prop_category'), True)
        self.assertEqual(hasattr(form_class, 'prop_link'), True)
        self.assertEqual(hasattr(form_class, 'prop_email'), True)
        self.assertEqual(hasattr(form_class, 'prop_geo_pt'), True)
        self.assertEqual(hasattr(form_class, 'prop_phone_number'), True)
        self.assertEqual(hasattr(form_class, 'prop_postal_address'), True)
        self.assertEqual(hasattr(form_class, 'prop_rating'), True)

        # These should NOT be set.
        self.assertEqual(hasattr(form_class, 'prop_list'), False)
        self.assertEqual(hasattr(form_class, 'prop_user'), False)
        self.assertEqual(hasattr(form_class, 'prop_im'), False)
예제 #9
0
    def get(self):
        
        self.context['message'] = 'Hello, World!'
        if self.request.args.has_key('key') and\
           self.request.args.has_key('remove'):
            
            key =  self.request.args.get('key')
            obj = SiteMonitor.getByID(key)
            obj.delete()
            
            return redirect('/sites')
        
        elif self.request.args.has_key('key'):
            key =  self.request.args.get('key')
            obj = SiteMonitor.getByID(key)
            
            MyForm = model_form(SiteMonitor, SiteMonitorForm)
            form = MyForm(self.request.form, obj)

            self.context['form'] = form
            
        else:
            self.context['form'] = SiteMonitorForm()
        
        return self.render_response('views/manage_sites.html', **self.context)
예제 #10
0
    def get_form(self, **kwargs):
        """Erzeuge Formularklasse für das Model"""

        # Erstmal nur das Form zurückgeben.
        # Soll sich doch jeder selbst um 'only' und 'exclude' kümmern,
        # bei model_form gehen aber leider alle Labels und Descriptions verloren.
        if hasattr(self, 'form'):
            return getattr(self, 'form')

        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)

        defaults = {
            'base_class': self.form,
            'only': self.fields,
            'exclude': (exclude + kwargs.get('exclude', [])) or None,
        }

        klass = model_form(self.model, **defaults)

        # label könnte man noch setzbar machen
        for blob_upload_field in self.blob_upload_fields:
            field = wtforms.FileField()
            setattr(klass, blob_upload_field, field)

        return klass
예제 #11
0
    def test_field_attributes(self):
        form_class = model_form(Author, field_args={
            'name': {
                'label': 'Full name',
                'description': 'Your name',
            },
            'age': {
                'label': 'Age',
                'validators': [validators.NumberRange(min=14, max=99)],
            },
            'city': {
                'label': 'City',
                'description': 'The city in which you live, not the one in which you were born.',
            },
            'is_admin': {
                'label': 'Administrative rights',
            },
        })
        form = form_class()

        self.assertEqual(form.name.label.text, 'Full name')
        self.assertEqual(form.name.description, 'Your name')

        self.assertEqual(form.age.label.text, 'Age')

        self.assertEqual(form.city.label.text, 'City')
        self.assertEqual(form.city.description, 'The city in which you live, not the one in which you were born.')

        self.assertEqual(form.is_admin.label.text, 'Administrative rights')
예제 #12
0
 def getForm( catid ):
     f = model_form( Categoria ) 
     if catid is None:
         return f()
     categoria = Categoria.getCategoriaById( catid )
     form = f( None, categoria )
     return form
예제 #13
0
 def getForm( tag ):
     f = model_form( DynamicHTML )
     if id is None:
         return f()
     html = DynamicHTML.getHTMLbyTag( tag )
     form  = f( None, html )
     return form
예제 #14
0
    def test_required_field(self):
        form_class = model_form(Author)

        form = form_class()
        self.assertEqual(form.name.flags.required, True)
        self.assertEqual(form.city.flags.required, False)
        self.assertEqual(form.age.flags.required, True)
        self.assertEqual(form.is_admin.flags.required, False)
예제 #15
0
    def test_default_value(self):
        form_class = model_form(Author)

        form = form_class()
        self.assertEqual(form.name.default, None)
        self.assertEqual(form.city.default, None)
        self.assertEqual(form.age.default, None)
        self.assertEqual(form.is_admin.default, False)
예제 #16
0
    def editUser(request, id):
        edit_form = model_form(User, Form)
        model = User.get(id);

        print(model)

        form = edit_form(request.form, model)
        print(form)
예제 #17
0
파일: tests.py 프로젝트: sskrab001/dpxdt
    def test_required_field(self):
        form_class = model_form(Author)

        form = form_class()
        self.assertEqual(form.name.flags.required, True)
        self.assertEqual(form.city.flags.required, False)
        self.assertEqual(form.age.flags.required, True)
        self.assertEqual(form.is_admin.flags.required, False)
예제 #18
0
파일: tests.py 프로젝트: sskrab001/dpxdt
    def test_default_value(self):
        form_class = model_form(Author)

        form = form_class()
        self.assertEqual(form.name.default, None)
        self.assertEqual(form.city.default, None)
        self.assertEqual(form.age.default, None)
        self.assertEqual(form.is_admin.default, False)
예제 #19
0
class OrganizationInformationForm(
        model_form(Organization,
                   only=[
                       'name', 'email', 'phone', 'url', 'twitter', 'facebook',
                       'address', 'city', 'state', 'zip_code', 'publish'
                   ]), OrganizationValidatorsMixIn):
    """ For editing of org by non-admin user. """
    pass
예제 #20
0
파일: __init__.py 프로젝트: Tapsa/Ferris
def model_form(model, *args, **kwargs):
    """
    Generates a Form class automatically from a Model class.
    For more information an the full list of arguments, see the `wtforms documentation <http://wtforms.simplecodes.com/docs/1.0.2/ext.html#module-wtforms.ext.appengine>`_.
    """
    if issubclass(model, db.Model):
        return wtfdb.model_form(model, *args, **kwargs)
    elif issubclass(model, ndb.Model):
        return wtfndb.model_form(model, *args, **kwargs)
예제 #21
0
def model_form(model, *args, **kwargs):
    """
    Generates a Form class automatically from a Model class.
    For more information an the full list of arguments, see the `wtforms documentation <http://wtforms.simplecodes.com/docs/1.0.2/ext.html#module-wtforms.ext.appengine>`_.
    """
    if issubclass(model, db.Model):
        return wtfdb.model_form(model, *args, **kwargs)
    elif issubclass(model, ndb.Model):
        return wtfndb.model_form(model, *args, **kwargs)
예제 #22
0
def edit(id):
    MyForm = model_form(MyModel, Form)
    model = MyModel.get(id)
    form = MyForm(request.form, model)

    if form.validate_on_submit():
        form.populate_obj(model)
        model.put() 
        flash("MyModel updated")
        return redirect(url_for("index"))
    return render_template("edit.html", form=form)
예제 #23
0
    def test_model_form_only(self):
        form_class = model_form(Author, only=['name', 'age'])

        self.assertEqual(hasattr(form_class, 'name'), True)
        self.assertEqual(hasattr(form_class, 'city'), False)
        self.assertEqual(hasattr(form_class, 'age'), True)
        self.assertEqual(hasattr(form_class, 'is_admin'), False)

        form = form_class()
        self.assertEqual(isinstance(form.name, f.TextField), True)
        self.assertEqual(isinstance(form.age, f.IntegerField), True)
예제 #24
0
파일: tests.py 프로젝트: sskrab001/dpxdt
    def test_model_form_only(self):
        form_class = model_form(Author, only=['name', 'age'])

        self.assertEqual(hasattr(form_class, 'name'), True)
        self.assertEqual(hasattr(form_class, 'city'), False)
        self.assertEqual(hasattr(form_class, 'age'), True)
        self.assertEqual(hasattr(form_class, 'is_admin'), False)

        form = form_class()
        self.assertEqual(isinstance(form.name, f.TextField), True)
        self.assertEqual(isinstance(form.age, f.IntegerField), True)
예제 #25
0
def edit(id):
    MyForm = model_form(MyModel, Form)
    model = MyModel.get(id)
    form = MyForm(request.form, model)

    if form.validate_on_submit():
        form.populate_obj(model)
        model.put()
        flash("MyModel updated")
        return redirect(url_for("index"))
    return render_template("edit.html", form=form)
예제 #26
0
 def get(self, key):
     
     _m = db.get(db.Key(key))
     if _m is not None:
         form = model_form(_m,exclude=_m.FORM_EXCLUDE)
         form.submit = fields.SubmitField()
         if self.request.args.get('edit', False):
             editform = True
         else:
             editform = False
     
     return self.render('admin/crud-view.html', object=_m, form=form(self.request.form, obj=_m), editform=editform)
예제 #27
0
    def test_populate_form(self):
        entity = Author(key_name='test', name='John', city='Yukon', age=25, is_admin=True)
        entity.put()

        obj = Author.get_by_key_name('test')
        form_class = model_form(Author)

        form = form_class(obj=obj)
        self.assertEqual(form.name.data, 'John')
        self.assertEqual(form.city.data, 'Yukon')
        self.assertEqual(form.age.data, 25)
        self.assertEqual(form.is_admin.data, True)
예제 #28
0
파일: tests.py 프로젝트: ascii1011/wtforms
    def test_populate_form(self):
        entity = Author(key_name='test', name='John', city='Yukon', age=25, is_admin=True)
        entity.put()

        obj = Author.get_by_key_name('test')
        form_class = model_form(Author)

        form = form_class(obj=obj)
        self.assertEqual(form.name.data, 'John')
        self.assertEqual(form.city.data, 'Yukon')
        self.assertEqual(form.age.data, 25)
        self.assertEqual(form.is_admin.data, True)
예제 #29
0
파일: views.py 프로젝트: wkomor/kws-blog
def edit(id):
    MyForm = model_form(BlogPost, Form)
    post = BlogPost.get_by_id(int(id))
    form = MyForm(request.form, post)

    if request.method == "POST":
        form.populate_obj(post)
        post.put()
        print post
        flash("Post updated")
        return redirect(url_for("admin_view"))
    return render_template("edit.html", form=form)
예제 #30
0
class NewEventForm(model_form(Event)):
    name = TextField('Name', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Name must be between 1 and 100 characters")
    ])
    short_name = TextField('Short Name', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Name must be between 1 and 100 characters")
    ])
예제 #31
0
파일: tests.py 프로젝트: sskrab001/dpxdt
    def test_model_form_basic(self):
        form_class = model_form(Author)

        self.assertEqual(hasattr(form_class, 'name'), True)
        self.assertEqual(hasattr(form_class, 'age'), True)
        self.assertEqual(hasattr(form_class, 'city'), True)
        self.assertEqual(hasattr(form_class, 'is_admin'), True)

        form = form_class()
        self.assertEqual(isinstance(form.name, f.TextField), True)
        self.assertEqual(isinstance(form.city, f.TextField), True)
        self.assertEqual(isinstance(form.age, f.IntegerField), True)
        self.assertEqual(isinstance(form.is_admin, f.BooleanField), True)
예제 #32
0
    def test_model_form_basic(self):
        form_class = model_form(Author)

        self.assertEqual(hasattr(form_class, 'name'), True)
        self.assertEqual(hasattr(form_class, 'age'), True)
        self.assertEqual(hasattr(form_class, 'city'), True)
        self.assertEqual(hasattr(form_class, 'is_admin'), True)

        form = form_class()
        self.assertEqual(isinstance(form.name, f.TextField), True)
        self.assertEqual(isinstance(form.city, f.TextField), True)
        self.assertEqual(isinstance(form.age, f.IntegerField), True)
        self.assertEqual(isinstance(form.is_admin, f.BooleanField), True)
예제 #33
0
    def test_reference_property(self):
        keys = ['__None']
        for name in ['foo', 'bar', 'baz']:
            author = Author(name=name, age=26)
            author.put()
            keys.append(str(author.key()))

        form_class = model_form(Book)
        form = form_class()

        i = 0
        for key, name, value in form.author.iter_choices():
            self.assertEqual(key, keys[i])
            i += 1
예제 #34
0
파일: tests.py 프로젝트: sskrab001/dpxdt
    def test_datetime_model(self):
        """Fields marked as auto_add / auto_add_now should not be included."""
        form_class = model_form(DateTimeModel)

        self.assertEqual(hasattr(form_class, 'prop_date_time_1'), True)
        self.assertEqual(hasattr(form_class, 'prop_date_time_2'), False)
        self.assertEqual(hasattr(form_class, 'prop_date_time_3'), False)

        self.assertEqual(hasattr(form_class, 'prop_date_1'), True)
        self.assertEqual(hasattr(form_class, 'prop_date_2'), False)
        self.assertEqual(hasattr(form_class, 'prop_date_3'), False)

        self.assertEqual(hasattr(form_class, 'prop_time_1'), True)
        self.assertEqual(hasattr(form_class, 'prop_time_2'), False)
        self.assertEqual(hasattr(form_class, 'prop_time_3'), False)
예제 #35
0
    def test_reference_property(self):
        keys = set(['__None'])
        for name in ['foo', 'bar', 'baz']:
            author = Author(name=name, age=26)
            author.put()
            keys.add(str(author.key()))

        form_class = model_form(Book)
        form = form_class()

        for key, name, value in form.author.iter_choices():
            assert key in keys
            keys.remove(key)

        assert not keys
예제 #36
0
    def test_reference_property(self):
        keys = ['__None']
        for name in ['foo', 'bar', 'baz']:
            author = Author(name=name, age=26)
            author.put()
            keys.append(str(author.key()))

        form_class = model_form(Book)
        form = form_class()

        choices = []
        i = 0
        for key, name, value in form.author.iter_choices():
            self.assertEqual(key, keys[i])
            i += 1
예제 #37
0
    def test_datetime_model(self):
        """Fields marked as auto_add / auto_add_now should not be included."""
        form_class = model_form(DateTimeModel)

        self.assertEqual(hasattr(form_class, 'prop_date_time_1'), True)
        self.assertEqual(hasattr(form_class, 'prop_date_time_2'), False)
        self.assertEqual(hasattr(form_class, 'prop_date_time_3'), False)

        self.assertEqual(hasattr(form_class, 'prop_date_1'), True)
        self.assertEqual(hasattr(form_class, 'prop_date_2'), False)
        self.assertEqual(hasattr(form_class, 'prop_date_3'), False)

        self.assertEqual(hasattr(form_class, 'prop_time_1'), True)
        self.assertEqual(hasattr(form_class, 'prop_time_2'), False)
        self.assertEqual(hasattr(form_class, 'prop_time_3'), False)
예제 #38
0
    def get_context(self, slug=None):
        postform = model_form(Post, exclude='slug, datepublished')

        if slug:
            post = Post.all().filter('slug =', slug).get()
            if request.method == 'POST':
                form = postform(request.form, inital=post._entity)
            else:
                form = postform(obj=post)
        else:
            post = Post(title='Untitled', content='Empty', slug='Empty')
            form = postform(request.form)

        context = {
            "post": post,
            "form": form,
            "create": slug is None
        }
        return context
예제 #39
0
def add_notes(agency):
 	MyForm = model_form(ProviderNotes, Form)
 	entity = db.Query(ProviderNotes).filter('provider_name =', agency).get()
 	if entity != None:
		form = MyForm(request.form, obj=entity)
		if form.validate_on_submit():
			form.populate_obj(entity)
			entity.put()
			flash(u'Example successfully saved.', 'success')
			return redirect(url_for('list_provs'))
	else:
		form = MyForm(request.form)
		if form.validate_on_submit():
			notes = ProviderNotes(
				provider_name=agency,
				provider_notes=form.provider_notes.data)
			notes.put()
			flash(u'Example successfully saved.', 'success')
			return redirect(url_for('list_provs'))
	return render_template('provider_notes.html', form=form, programs=list_addresses(agency), pname=agency, notes=list_notes(agency))
예제 #40
0
def create(model, only=None, exclude=None, base_class=WTForm, converter=None,
           pre_init=None, post_init=None, pre_save=None, post_save=None,
           field_validators=None):
  '''Factory for admin forms.

  Input:
    * model - class to be used for wtforms creation
    * only - tuple of field names that should be exposed in the form
    * exclude - marked separately as read-only when editing,
                but still editable for new instances

  All the following receive the form and the object as parameters:
  (Note that the object may be None for new model instances)
    * pre_init - hook called before initializing the form, for a chance to
                 modify the instance before editing
    * post_init - hook called immediately after initializing the form, can be useful
                  to modify the form before display
    * pre_save, post_save - hooks called before/after saving an item

  All the following receive the form and the field as parameters:
    * field_validators - a dict of field -> callback function for validating
                         individual properties
  '''
  converter = converter or AdminConverter(model)
  form = model_form(
    model=model, base_class=base_class, only=only, exclude=exclude, converter=converter)
  form.model = model
  form.pre_init = pre_init
  form.post_init = post_init
  form.pre_save = pre_save
  form.post_save = post_save
  if field_validators:
    for field_name, validators in field_validators.items():
      if not isinstance(validators, (list, tuple)):
        field_validators[field_name] = [validators]
  form.field_validators = field_validators
  form.converter = converter
  return form
예제 #41
0
 def index(self):
     from flask_wtf import Form
     from wtforms.ext.appengine.db import model_form
     from budgetfamily.payment.models import Salary
     form = model_form(Salary, Form)
     return self.render('income_view.html', form=form)
예제 #42
0
from wtforms.ext.appengine.db import model_form
from wtforms import form, fields, validators
from models import Style, Invitation, Site

SiteForm = model_form(Site, only=['name'])

StyleForm = model_form(Style, only=['name'])

InviteForm = model_form(Invitation, only=['email', 'admin'])

def add_protocol(url):
    if not url.startswith('http://') and not url.startswith('https://'):
        return 'http://' + url
    else:
        return url

class PageForm(form.Form):
    name = fields.TextField('Name', [validators.required(), validators.length(max=500)])
    url = fields.TextField('URL', [validators.required(), validators.URL(require_tld=False), validators.length(max=1024)])
    preview_urls = fields.FieldList(fields.TextField('Additional preview URLs', [validators.URL(require_tld=False), validators.length(max=1024)]))

    def validate(self):
        self.url.data = add_protocol(self.url.data)
        for ix in range(len(self.preview_urls)):
            self.preview_urls[ix].data = add_protocol(self.preview_urls[ix].data)
        return form.Form.validate(self)
예제 #43
0
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__))))

from flask import render_template, url_for, redirect
from flaskext.wtf import Form
from wtforms.ext.appengine.db import model_form
from wtforms import validators

from app import app
from models import MyModel

MyForm = model_form(
    MyModel,
    Form,
    field_args={'name': {
        'validators': [validators.Length(max=10)]
    }})


@app.route("/edit<id>")
def edit(id):
    MyForm = model_form(MyModel, Form)
    model = MyModel.get(id)
    form = MyForm(request.form, model)

    if form.validate_on_submit():
        form.populate_obj(model)
        model.put()
        flash("MyModel updated")
        return redirect(url_for("index"))
예제 #44
0
# coding: utf-8

from wtforms.ext.appengine.db import model_form

from models import *

SkillForm = model_form(Skill, exclude = ('count'))

ResourceForm = model_form(Resource, exclude = ('count'))

예제 #45
0
from wtforms.ext.appengine.db import model_form
from models import *
from copy import copy

GameObjectForm = model_form(GameObject)
VisualGameObjectForm = model_form(VisualGameObject)
ModifierForm = model_form(Modifier)
InteractionForm = model_form(Interaction)
LevelForm = model_form(Level)
EquipmentForm = model_form(Equipment)
VehicleForm = model_form(Vehicle)
ObjectiveForm = model_form(Objective)
MissionForm = model_form(Mission)
TeamForm = model_form(Team)
SkillForm = model_form(Skill)
AttributeForm = model_form(Attribute)
NPCForm = model_form(NPC)
CharacterForm = model_form(Character)
PlayerForm = model_form(Player)
GameForm = model_form(Player)
EventForm = model_form(Event)

EnvironmentForm = model_form(Environment)

BaseGraphicForm = model_form(Graphic)
del BaseGraphicForm.path

class GraphicForm(BaseGraphicForm):
  formdata = None
  
  def __init__(self, data=None):
예제 #46
0
 def getForm( ):
     f = model_form( CSS )
     css = CSS().get( )
     form  = f( None, css )
     return form
예제 #47
0
def new_meeting_form(handler):
    return model_form(Meeting, exclude=('minute'), base_class=BaseForm, converter=I18nConverter(handler.locale), field_args={
                'day': {
                    'label': handler.locale.translate('When?')
                }
            })(handler=handler)
예제 #48
0
파일: mchopa_admin.py 프로젝트: dbow/MCHOPA
    autoescape=True)


#Painting outlines the database entity for the paintings
class Painting(db.Model):
  idnumber = db.IntegerProperty()
  title = db.StringProperty(required=True)
  description = db.StringProperty(multiline=True, required=True)
  filename = db.StringProperty(required=True)
  size = db.StringProperty(required=True, choices=['10x14', '12x28', '17x28', '23x31', '20x24',])
  price = db.IntegerProperty(required=True)
  series = db.StringProperty(choices=['','Classic', 'Illustrative', 'Abstract'])
  status = db.StringProperty(required=True, choices=['Available', 'Sold', 'Reserved'])


PaintingForm = model_form(Painting, exclude=('idnumber'))

#This class constructs the admin dashboard, listing all the paintings and any messages based on URL parameters
class AdminDashboard(webapp2.RequestHandler):
  def get(self):
    paintings = db.GqlQuery("SELECT * FROM Painting ORDER BY idnumber")

    #Extract any URL parameters
    error = self.request.get('error')
    added = self.request.get('added')
    dup = self.request.get('dup')
    deleted = self.request.get('deleted')

    #Display messages based on those parameters
    if error == str(0):
      error = "Please attach an Excel CSV file to upload"
예제 #49
0
class OrganizationAdminForm(model_form(Organization)):
    # TODO: replace with a sub-class of a newer model form
    contact_first_name = TextField('First Name', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Your name must be between 1 and 100 characters")
    ])

    contact_last_name = TextField('Last Name', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Your name must be between 1 and 100 characters")
    ])
    contact_email = TextField('Your Email', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Your email must be between 1 and 100 characters"),
        validators.Email(message="That's not a valid email address.")
    ])
    contact_phone = TextField('Your Phone Number', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Your phone must be between 1 and 100 characters")
    ])
    name = TextField('Organization Name', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Organization Name must be between 1 and 100 characters")
    ])
    email = TextField('Organization Email', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Name must be between 1 and 100 characters"),
        validators.Email(message="That's not a valid email address.")
    ])
    phone = TextField('Organization Phone Number', [
        wtforms.validators.Length(
            min=1,
            max=100,
            message="Organization phone must be between 1 and 100 characters")
    ])
    address = TextField('Address')
    city = TextField('City')
    state = TextField('State')
    zip_code = TextField('Zip Code')
    url = TextField('Organization URL', [
        wtforms.validators.Length(
            min=0,
            max=100,
            message="Organization URL must be between 0 and 100 characters")
    ])
    twitter = TextField('Organization Twitter', [
        wtforms.validators.Length(
            min=0,
            max=16,
            message="Twitter handle must be between 0 and 16 characters")
    ])
    facebook = TextField('Facebook link', [
        wtforms.validators.Length(
            min=0,
            max=100,
            message="Facebook link must be between 0 and 100 characters")
    ])
예제 #50
0
class StandardSiteForm(model_form(Site)):
    pass
예제 #51
0
#coding=utf-8
from flask_wtf import Form
from wtforms.ext.appengine.db import model_form
from wtforms import validators
from .models import SysConfig
"""http://flask.pocoo.org/snippets/60/
Automatically create a WTForms Form from model
"""
SysConfigForm = model_form(
    SysConfig,
    Form,
    field_args={'web_name': {
        'validators': [validators.Length(max=5)]
    }})
"""example:

from flaskext.wtf import Form
from wtforms.ext.appengine.db import model_form
from models import MyModel

@app.route("/edit<id>")
def edit(id):
    MyForm = model_form(MyModel, Form)
    model = MyModel.get(id)
    form = MyForm(request.form, model)

    if form.validate_on_submit():
        form.populate_obj(model)
        model.put() 
        flash("MyModel updated")
        return redirect(url_for("index"))
예제 #52
0
from wtforms import Form
from wtforms.ext.appengine.db import model_form
from models import *

from wtforms import BooleanField, TextField, validators, DateTimeField

MedKit_meta = model_form(MedKit, base_class=Form)
Volunteer_meta = model_form(Volunteer, base_class=Form)
SupplyForm = model_form(Supply, base_class=Form)
DeliveryEventForm = model_form(DeliveryEvent, base_class=Form)

class VolunteerForm(Volunteer_meta):
    cos = DateTimeField('COS', format='%m/%d/%Y')


SupplyRequestForm = model_form(SupplyRequest, base_class=Form, exclude=['quantities', 'supplies', 'date', 'delivery_event'])
예제 #53
0
파일: main.py 프로젝트: greggy/gae-blog
from wtforms.ext.appengine.db import model_form

from models import *
from utils import render


# Forms
post = Post()
error_message = u'Это поле обязательно для заполнения.'
PostForm = model_form(Post, only=('title', 'slug', 'content', 'published'), field_args={
    'title': {
        'validators': [validators.Required(message = error_message)],
        'label': u'Заголовок'
    }, 'slug': {
        'validators': [validators.Required(message = error_message)],
        'label': u'Слаг'
    }, 'content': {
        'validators': [validators.Required(message = error_message)],
        'label': u'Тело статьи'
    }, 'published': {
        'label': u'Опубликовать'
    }
})
    
# Handlers
class MainHandler(webapp.RequestHandler):
    def get(self):
        posts = Post.all()
        posts.filter('published =', True).order('-date_posted').fetch(10)
        context = {
            #'user': user,
            'posts': posts[:10],
예제 #54
0
            return []
        return [ image ]


class WobForm(Form):
    """WobForm allows me to extend the wtforms.Form"""
    # I'm sure there's more clever ways to do this, but this works
    @classmethod
    def hasImageField(cls, name):
        fieldClass = getattr(getattr(cls, name, object), 'field_class', None)
        return issubclass(fieldClass, ImageField)


ModelCountryForm = model_form(Country, WobForm,
                              field_args = 
                              { 
                               "perCapBeer": { "label": "Beer consumed per capita" },
                               "totBeer":    { "label": "Total beer consumption" }, 
                              })
class CountryForm(ModelCountryForm):
    flag = ImagePreviewField(**ModelCountryForm.flag.kwargs)
    map  = ImagePreviewField(**ModelCountryForm.map.kwargs)


ModelBreweryForm = model_form(Brewery, WobForm)
class BreweryForm(ModelBreweryForm):
    logo = ImagePreviewField(**ModelBreweryForm.logo.kwargs)


ModelBeerForm = model_form(Beer, WobForm)
class BeerForm(ModelBeerForm):
    picture = ImagePreviewField(**ModelBeerForm.picture.kwargs)
예제 #55
0
class AddAdminForm(AddUserForm):
    account_type = SelectField(u'User type')
   
SessionDataForm = db.model_form(SessionData, base_class=Form, field_args={
   'users': {
       'label': 'User Id',
       'description': '',
       'validators': [validators.Required()]
   },
   'name': {
       'label': 'Session Name',
       'description': '',
       'validators': [validators.Required()]
   },
   'room': {
       'label': 'Session Room',
       'description': '',

   },

   }, exclude=('date_time','module',
            'blob_store_key',
            'filename',
            'dbox_path',
            'uploaded_to_dbox',
            'dbox_size'))

UserDataForm = ndb.model_form(User, base_class=Form, field_args={
  'firstname': {
       'label': 'First Name',