def get_or_post(self): if self.request.POST: new_entity = Contact( key_name=self.request.get('key_name'), name=self.request.get('name'), age=int(self.request.get('age')), state=self.request.get('state')) new_entity.put() # Generate a form based on the model. ContactForm = model_form(Contact) # Get a form populated with entity data. #entity = Contact.get_by_key_name('test') #keys = ['test'] #entity = ndb.get_multi([ndb.Key('Contact', 'test')]) entitylist = Contact.query().order(-Contact.created).fetch(1) logging.info('QQQ: entitylist: %s' % entitylist) if len(entitylist) > 0: form = ContactForm(obj=entitylist[0]) else: form = ContactForm() #Properties from the model can be excluded from the generated form, or it can #include just a set of properties. For example: # #.. code-block:: python # Generate a form based on the model, excluding 'city' and 'is_admin'. ContactForm = model_form(Contact, exclude=('city', 'is_admin')) # or... # Generate a form based on the model, only including 'name' and 'age'. ContactForm = model_form(Contact, only=('name', 'age')) #The form can be generated setting field arguments: # #.. code-block:: python # ContactForm = model_form( Contact, only=('name', 'age'), field_args={ 'name': { 'label': 'Full name', 'description': 'Your name', }, 'age': { 'label': 'Age', #'validators': [validators.NumberRange(min=14, max=99)], } }) logging.info('contactform3: %s' % ContactForm) #self.response.out.write('contactform3: %s' % ContactForm) template_values = {'form': form} template = jinja_environment.get_template('stdpage_block.html') self.response.out.write(template.render(template_values))
def beermenu_edit_item(request, user): reqid = int(request.form['id']) item = models.BeerMenu.get_by_id(reqid, parent=None) old_item = item.to_dict().copy() if item: form = model_form(models.BeerMenu) form_object = form(formdata=request.form) if not form_object.errors and form_object.validate(): form_object.populate_obj(item) # why the F does false not get detected correctly if request.form['active'] == 'false': item.active = False item_key = item.put() if request.form['freshest'] == "true": beermenu_set_freshest(item_key.id()) # write audit log new_item = item.to_dict() item_beerid = item_key.id() write_auditlog(old_item, new_item, item_beerid, user, request.form['oper']) response = 'OK:\n user: %s\n oper: %s\n beerid: %s\n changed: %s\n' % (user, request.form['oper'], item_beerid, new_item) clear_caches_beermenu() return response else: response = '%s\n %s' % (form_object.errors, form_object.validate()) return response else: return 'item not found!!\n'
def create(self): """ Create method Create a new resource using posted data """ # create form instance from the ResourceModel resource_model_form = model_form(ResourceModel) form = resource_model_form(self.request.POST) context = { 'action': 'New', 'form': form, 'submit_routename': 'resource.create' } # since this method is only called from a post, # we do not need to check for request.method == "POST" # if self.form.validate() returns true, then save # the data if form.validate(): logging.debug('Form Validated!') entity = ResourceModel() # push form values into model form.populate_obj(entity) # save to data store key = entity.put() # redirect to index and/or edit form with new id logging.debug('key={0}'.format(key)) # redirect to the edit page for the created id return webapp2.redirect_to('resource.edit', id=key.id()) # the form did not validate, redisplay with errors return self.render_response('resource.html', context)
def test_book(self): authors = set(text_type(x.key.id()) for x in fill_authors(Author)) authors.add('__None') form = model_form(Book) keys = set() for key, b, c in form().author.iter_choices(): keys.add(key) self.assertEqual(authors, keys)
def form(self): """ Reference to the WTForm object This is used to inject self.form into the template context. """ # Generate a form based on the model. ResourceModelForm = model_form(ResourceModel) # create and return an instance of the form based on # the ResourceModel return ResourceModelForm
def new(self): """ New method Gather input to create a new resource """ resource_model_form = model_form(ResourceModel) form = resource_model_form(self.request.POST) context = { 'action': 'New', 'form': form, 'submit_routename': 'resource.create' } self.render_response('resource.html', context)
def bottlemenu_add_item(request, user): form = model_form(models.BottleMenu) form_object = form(formdata=request.form) if not form_object.errors and form_object.validate(): item = models.BottleMenu() form_object.populate_obj(item) if request.form['active'] == 'false': item.active = False item_key = item.put() # write audit log item_beerid = item_key.id() new_item = item.to_dict() response = 'OK:\n user: %s\n oper: %s\n beerid: %s\n changed: %s\n' % (user, request.form['oper'], item_beerid, new_item) clear_caches_bottlemenu() return response else: response = '%s\n %s' % (form_object.errors, form_object.validate()) return response
def edit(self, id): """ Edit method Edit a specific resource by id """ entity_id = int(id) resource_model_form = model_form(ResourceModel) entity = ResourceModel.get_by_id(entity_id) form = resource_model_form(self.request.POST, obj=entity) context = { 'action': 'Edit', 'id': id, 'form': form, 'submit_routename': 'resource.update' } self.render_response('resource.html', context)
""" from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import ExampleModel, CatalogModel class ClassicExampleForm(wtf.Form): example_name = wtf.TextField('Name', validators=[validators.Required()]) example_description = wtf.TextAreaField( 'Description', validators=[validators.Required()]) class ClassicCatalogForm(wtf.Form): ctlg_name = wtf.TextField('Name', validators=[validators.Required()]) ctlg_desc = wtf.TextAreaField( 'Description', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, wtf.Form, field_args={ 'example_name': dict(validators=[validators.Required()]), 'example_description': dict(validators=[validators.Required()]), }) CatalogForm = model_form(CatalogModel, wtf.Form, field_args={ 'ctlg_name': dict(validators=[validators.Required()]), 'ctlg_desc': dict(validators=[validators.Required()]), })
Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from wtforms.ext.appengine.ndb import model_form from .models import Conference from wtforms.widgets.core import Input ConferenceForm = model_form(Conference, wtf.Form, exclude=['organizer', 'num_tix_available'], field_args={ 'name': dict( label='Conference Title' ), 'desc': dict( label='Description' ), 'start_date': dict( widget=Input(input_type='date') ), 'end_date': dict( widget=Input(input_type='date') ), })
""" forms.py Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flask.ext.wtf import Form from wtforms.ext.appengine.ndb import model_form from wtforms.fields import TextField, TextAreaField from wtforms import validators from application.models.ExampleModel import ExampleModel class ClassicExampleForm(Form): example_name = TextField('Name', validators=[validators.Required()]) example_description = TextAreaField('Description', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, Form, field_args={ 'example_name': dict(validators=[validators.Required()]), 'example_description': dict(validators=[validators.Required()]), })
forms.py Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from models import ExampleModel, UserModel class ClassicExampleForm(wtf.Form): example_name = wtf.TextField('Name', validators=[validators.Required()]) example_description = wtf.TextAreaField('Description', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, wtf.Form, field_args={ 'example_name': dict(validators=[validators.Required()]), 'example_description': dict(validators=[validators.Required()]), }) UserForm = model_form(UserModel, wtf.Form, field_args={ "name": dict(validators=[validators.Required()]) })
Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import SchoolModel class ClassicExampleForm(wtf.Form): example_name = wtf.TextField('Name', validators=[validators.Required()]) example_description = wtf.TextAreaField('Description', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(SchoolModel, wtf.Form, field_args={ 'example_name': dict(validators=[validators.Required()]), 'example_description': dict(validators=[validators.Required()]), })
""" from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from application import app from .models import TicketModel # Main form TikcetForm = model_form( TicketModel, wtf.Form, only=[ "email" ], field_args={ "email": dict(validators=[validators.Regexp(regex="^[A-Za-z0-9._%+\-\ ]+@[A-Za-z0-9.\-\ ]+\.[A-Za-z]{2,4}([\ ]+)?$")]), } ) TikcetForm.payment_method = wtf.SelectField( choices=[ ("BTC", "Bitcoin"), ("PAYPAL", "PayPal"), ("WIRETRANSFER", "Bank Transfer") ] ) TikcetForm.ticket_type = wtf.SelectField( choices=[
from flask_wtf import Form from wtforms.ext.appengine.ndb import model_form from wtforms.fields import StringField, HiddenField, PasswordField from wtforms import validators from family.models.member import Profile from family.models.message import Message BaseProfileForm = model_form(Profile, Form, field_args={ 'birth_date': {'validators': [validators.optional()]}} # disable DateField validator ) class MemberProfileForm(BaseProfileForm): member_id = HiddenField() first_name = StringField('First Name', [validators.input_required()]) last_name = StringField('Last Name', [validators.input_required()]) class ChangePasswordForm(Form): old_password = PasswordField('Old Password', [validators.input_required()]) new_password = PasswordField('New Password', [ validators.input_required(), validators.equal_to('confirm_password', message='Passwords must match') ]) confirm_password = PasswordField('Re-type New Password', [ validators.input_required(), validators.equal_to('new_password', message='Passwords must match') ])
def add(self): # a custom form exclude "views" property PostForm = model_form(self.meta.Model, exclude=('views',)) # override model form of BasicModel self.scaffold.ModelForm = PostForm return scaffold.add(self)
def default_form(cls): ''' if self.form not set it will render the default model_form ''' form = model_form(cls.model) return form
from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import TemperatureReadingBatch, TemperatureSetting def validate_json(form, field): """Raise a validationerror if field is not json""" try: json.loads(field.data) except: raise wtf.ValidationError("Is not valid json") class TemperatureReadingBaseForm(wtf.Form): durable = wtf.fields.BooleanField('Store durably') TemperatureReadingBatchForm = model_form(TemperatureReadingBatch, TemperatureReadingBaseForm, field_args={ 'name': dict(validators=[validators.Required()]), 'source': dict(validators=[validators.Required()]), 'temp_readings_c': dict(validators=[validators.Required(), validate_json]), }) TemperatureSettingForm = model_form(TemperatureSetting, wtf.Form, field_args={ 'name': dict(validators=[validators.Required()]), 'target': dict(validators=[validators.Required()]), 'temp_c': dict(validators=[validators.NumberRange(), validators.Required()]), })
""" forms.py Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import ProviderModel # class ClassicExampleForm(wtf.Form): # example_name = wtf.TextField('Name', validators=[validators.Required()]) # example_description = wtf.TextAreaField('Description', validators=[validators.Required()]) # App Engine ndb model form example ProviderForm = model_form(ProviderModel, wtf.Form, field_args={ 'trading_name': dict(validators=[validators.Required()]), 'phone_number': dict(validators=[validators.Required()]), 'post_code': dict(validators=[validators.Required()]), })
""" from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import ExampleModel class ClassicExampleForm(wtf.Form): example_name = wtf.TextField('Name', validators=[validators.Required()]) example_description = wtf.TextAreaField('Description', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, wtf.Form, field_args={ 'example_name': dict(validators=[validators.Required()], label='Map Name'), 'example_description': dict(validators=[validators.Required()], label='Map Description'), }) class NewDialogForm(wtf.Form): cmb_map = wtf.SelectField('Map:', choices = [('Map one', 'Map one'), ('Map two', 'Map two'), ('Map three', ' Map three')], validators=[validators.Required()]) cmb_unit = wtf.SelectField('Unit:', choices = [('Unit one', 'Unit one'), ('Unit two', 'Unit two'), ('Unit three', ' Unit three')], validators=[validators.Required()]) text_description = wtf.TextAreaField('Description:', validators=[validators.Required()]) class QuickListForm(wtf.Form): cmb_map = wtf.SelectField('Map:',
class ClassicExampleForm(wtf.Form): example_name = wtf.TextField('Name', validators=[validators.Required()]) example_description = wtf.TextAreaField('Description', validators=[validators.Required()]) class AddressForm(wtf.Form): street = wtf.TextField('Street', validators=[validators.Required()]) suite = wtf.TextField('Suite') city = wtf.TextField('City', validators=[validators.Required()]) state = wtf.TextField('State', validators=[validators.Required()]) zip = wtf.TextField('Zip', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, wtf.Form, field_args={ 'example_name': dict(validators=[validators.Required()]), 'example_description': dict(validators=[validators.Required()]), }) PartyBaseForm = model_form(Party, wtf.Form) class PartyForm(PartyBaseForm): street = AddressForm.street suite = AddressForm.suite city = AddressForm.city state = AddressForm.state zip = AddressForm.zip EditRSVP = model_form(Person, wtf.Form, field_args={ 'rsvp': dict(validators=[validators.Required()]), })
""" forms.py Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import SongModel class ClassicSongForm(wtf.Form): name = wtf.TextField('Name', validators=[validators.Required()]) content = wtf.TextAreaField('Song') class ImportForm(wtf.Form): json = wtf.FileField('Import song:', validators=[validators.Required()]) # App Engine ndb model form song SongForm = model_form(SongModel, wtf.Form, field_args={ 'name': dict(validators=[validators.Required()]), 'content': dict(), })
class ClassicExampleForm(wtf.Form): example_name = wtf.TextField('Name', validators=[validators.Required()]) example_description = wtf.TextAreaField('Description', validators=[validators.Required()]) class ClassicCatalogForm(wtf.Form): ctlg_name = wtf.TextField('Name', validators=[validators.Required()]) ctlg_desc = wtf.TextAreaField('Description', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, wtf.Form, field_args={ 'example_name': dict(validators=[validators.Required()]), 'example_description': dict(validators=[validators.Required()]), }) CatalogForm = model_form(CatalogModel, wtf.Form, field_args={ 'ctlg_name': dict(validators=[validators.Required()]), 'ctlg_desc': dict(validators=[validators.Required()]), })
from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import Chore # A form which uses a Chore as its model ChoreForm = model_form(Chore, wtf.Form, field_args={ 'title': dict(validators=[validators.Required()]), 'content': dict(validators=[validators.Required()]), })
def test(self): form = model_form(Author) for (expected_name, expected_type), field in zip(self.EXPECTED_AUTHOR, form()): self.assertEqual(field.name, expected_name) self.assertEqual(type(field), expected_type)
from flask_wtf import Form from wtforms.ext.appengine.ndb import model_form from app.models import SiteMember, Message SiteMemberForm = model_form(SiteMember, Form) MessageForm = model_form(Message, Form)
def add(self): # a custom form exclude "views" property PostForm = model_form(self.meta.Model, exclude=('views', )) # override model form of BasicModel self.scaffold.ModelForm = PostForm return scaffold.add(self)
""" from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import Question, Answer, QuestionSearch, ProspectiveUser class ClassicQuestionSearchForm(wtf.Form): latitude = wtf.DecimalField('Latitude', validators=[validators.Required()]) longitude = wtf.DecimalField('Longitude', validators=[validators.Required()]) distance_in_km = wtf.DecimalField('Distance (km)', validators=[validators.Required()]) QuestionSearchForm = model_form(QuestionSearch, wtf.Form, field_args={ 'latitude': dict(validators=[validators.Required()]), 'longitude': dict(validators=[validators.Required()]), 'distance_in_km': dict(validators=[validators.Required()]), }) ProspectiveUserForm = model_form(ProspectiveUser, wtf.Form, field_args={ 'login': dict(validators=[validators.Required()]), 'origin_location': dict(validators=[validators.Required()]), 'notification_radius_in_km': dict(validators=[validators.Required()]), 'screen_name': dict(validators=[validators.Required()]), }) class QuestionForm(wtf.Form): content = wtf.TextAreaField('Content', validators=[validators.Required()]) location = wtf.TextField('Location', validators=[validators.Required()])
""" from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from models import ExampleModel, UserModel class ClassicExampleForm(wtf.Form): example_name = wtf.TextField('Name', validators=[validators.Required()]) example_description = wtf.TextAreaField('Description', validators=[validators.Required()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, wtf.Form, field_args={ 'example_name': dict(validators=[validators.Required()]), 'example_description': dict(validators=[validators.Required()]), }) UserForm = model_form( UserModel, wtf.Form, field_args={"name": dict(validators=[validators.Required()])})
}, 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', 'description': '', 'validators': [validators.Required()] }, 'lastname': { 'label': 'Last Name', 'description': '', 'validators': [validators.Required()] }, 'email_address': { 'label': 'Email', 'description': '', 'validators': [validators.Required()] }, }, exclude=('module', 'password', 'account_type')) ConferenceDataForm = db.model_form(ConferenceData, base_class=Form, field_args={ 'c_client': { 'label': 'Client Name', 'description': '', 'validators': [validators.Required()] },
if not rv: return False user = Users.get_by_username(self.username.data) if not user: self.username.errors.append('User does not exist') return False if not user.verify_password(self.password.data): self.password.errors.append('Password incorrect') return False self.user = user return True RegisterForm = model_form(Users, Form) class RegisterFormExt(RegisterForm): password = PasswordField('Password', [validators.DataRequired(), validators.EqualTo('confirm_password', message='Password does not match')]) confirm_password = PasswordField('Confirm Password', [validators.DataRequired()]) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) def validate(self): rv = Form.validate(self) if not rv: return False
""" forms.py Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from models import CleanUserProcess CleanUserProcessForm = model_form(CleanUserProcess, wtf.Form,field_args={ 'name':dict(validators=[validators.Required()]), 'source_email': dict(validators=[validators.Required(),validators.Email()]), 'source_password': dict(validators=[validators.Required()]), },exclude=['destination_message_email','owner_email', 'credentials','refresh_token','status','pipeline_id', 'number_of_messages', 'progress']) class MoveProssessForm(wtf.Form): emails = wtf.TextAreaField('emails', validators=[validators.Required()]) tag = wtf.TextField('tag', validators=[validators.Required()])
DEBUG=False ) USERS = tuple('DXLR') class Expense(ndb.Model): """Expense entity""" item_name = ndb.StringProperty(required=True) amount = ndb.FloatProperty(required=True) purchase_date = ndb.DateProperty() timestamp = ndb.DateTimeProperty(auto_now_add=True) ExpenseForm = model_form(Expense, field_args={ 'item_name': dict(validators=[validators.Required()]), 'amount': dict(validators=[validators.Required()]), }) @app.route('/') def index(): """Show the default view""" form = ExpenseForm() return render_template('index.html', form=form) @app.route('/', methods=['POST']) def new(): form = ExpenseForm() if request.method == 'POST' and form.validate(): flash('Success', 'success') return "submitted"
Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flask_wtf import form from wtforms import fields, validators from wtforms.ext.appengine.ndb import model_form from models import ExampleModel class ClassicExampleForm(form.FlaskForm): example_name = fields.StringField('Name', validators=[validators.DataRequired()]) example_description = fields.TextAreaField( 'Description', validators=[validators.DataRequired()]) # App Engine ndb model form example ExampleForm = model_form(ExampleModel, form.FlaskForm, field_args={ 'example_name': dict(validators=[validators.DataRequired()]), 'example_description': dict(validators=[validators.DataRequired()]), })
See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import Post class ClassicPostForm(wtf.Form): post_title = wtf.TextField("Title", validators=[validators.Required()]) post_slug = wtf.TextField("Slug", validators=[validators.Required()]) post_body = wtf.TextAreaField("Body", validators=[validators.Required()], id="source") post_tags = wtf.TextField("Tags", validators=[validators.Required()]) PostForm = model_form( Post, ClassicPostForm, field_args={ "post_title": dict(validators=[validators.Required()]), "post_slug": dict(validators=[validators.Required()]), "post_body": dict(validators=[validators.Required()]), "post_tags": dict(validators=[validators.Required()]), }, )
Web forms based on Flask-WTForms See: http://flask.pocoo.org/docs/patterns/wtforms/ http://wtforms.simplecodes.com/ """ from flaskext import wtf from flaskext.wtf import validators from wtforms.ext.appengine.ndb import model_form from .models import SongModel class ClassicSongForm(wtf.Form): name = wtf.TextField('Name', validators=[validators.Required()]) content = wtf.TextAreaField('Song') class ImportForm(wtf.Form): json = wtf.FileField('Import song:', validators=[validators.Required()]) # App Engine ndb model form song SongForm = model_form(SongModel, wtf.Form, field_args={ 'name': dict(validators=[validators.Required()]), 'content': dict(), })
from models import NetworkService, ApiAuthorisation, ServiceLocation, LogEntry, EventLog from serviceparser import parse_service_list, parse_contact_list from settings import cookie_secret, csrf_secret from routes import routes from utils import on_production_server, flatten, from_isodatetime mimerender = mimerender.Webapp2MimeRender() templates = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__),'templates') ), extensions=['jinja2.ext.autoescape']) NetworkServiceForm = model_form(NetworkService, exclude=('md','pt',)) class RequestHandler(webapp2.RequestHandler): CLIENT_COOKIE_NAME='discovery' CSRF_COOKIE_NAME='csrf' def create_context(self, **kwargs): route = routes[self.request.route.name] context = { "title": kwargs.get('title', route.title), "uri_for":self.uri_for, "on_production_server":on_production_server } #parent = app.router.match() #(route, args, kwargs) for k,v in kwargs.iteritems():