def build_form_renderer(): """ Builds the form handler by creating and adding the forms. """ # build forms membership_listing_date_pdf_form = deform.Form( MembershipListingDate(), buttons=[deform.Button('submit', _(u'Generate PDF'))], formid='membership_listing_date_pdf') membership_listing_year_end_pdf_form = deform.Form( MembershipListingYearEnd(), buttons=[deform.Button('submit', _(u'Generate PDF'))], formid='membership_listing_year_end_pdf') # create form handler form_renderer = MultipleFormRenderer() # add forms form_renderer.add_form(membership_listing_date_pdf_form, membership_listing_date_pdf_callback) form_renderer.add_form(membership_listing_year_end_pdf_form, membership_listing_date_pdf_callback) return form_renderer
def action_create(self): schema = self.model_schema_cls().bind() form = deform.Form(schema, buttons=(deform.Button(title='Create'), deform.Button(title='Cancel', type='reset', name='cancel'))) if 'submit' in self.request.POST: try: data = form.validate(self.request.POST.items()) data = _colander_null_to_none(data) obj = self.admin_mgr.create(data) self.request.session.flash(u'"%s" was created successful.' % obj, queue='pyramid_admin') return HTTPFound(_rsr.object_url(self.request, obj)) except deform.ValidationFailure as e: pass return { 'view': self, "form": form, 'admin_mgr': self.admin_mgr, }
def action_update(self): obj = self.context.object schema = self.model_schema_cls().bind(obj=obj) """:type schema: colander.Schema""" appstruct = _none_to_colander_null( {k: obj.__getattribute__(k) for k in self.admin_mgr.column_names}) form = deform.Form(schema, appstruct=appstruct, buttons=(deform.Button(title='Update'), deform.Button(title='Cancel', type='reset', name='cancel'))) if 'submit' in self.request.POST: try: data = form.validate(self.request.POST.items()) data = _colander_null_to_none(data) obj = self.admin_mgr.update(obj, data) self.request.session.flash(u'"%s" was updated successful.' % obj, queue='pyramid_admin') return HTTPFound(_rsr.object_url(self.request, obj)) except deform.ValidationFailure as e: pass return { 'view': self, 'obj': obj, "form": form, 'admin_mgr': self.admin_mgr, }
def register_nonmember_form(): return deform.Form(action="/register", schema=RegisterNonmemberSchema(), buttons=[ deform.Button('register_webuser', _(u"Register"), css_class="btn-lg"), deform.Button('back', _(u"Back")) ])
def buttons(self): return ( deform.Button('login', title=_(u"Login"), css_class='btn btn-primary'), deform.Button('recover', title=_(u"Recover password"), css_class='btn btn-primary'), self.button_cancel, )
def claims_membership_form(): return deform.Form(action="/register", title=_(u"Are you a C3S member?"), schema=colander.MappingSchema(), buttons=[ deform.Button('claims_membership', _(u"Yes"), css_class="btn-default btn-lg"), deform.Button('claims_no_membership', _(u"No")) ])
def wants_membership_form(): return deform.Form(action="/register", title=_(u"Do you want to apply for C3S membership?"), schema=colander.MappingSchema(), buttons=[ deform.Button('wants_membership', _(u"Yes"), css_class="btn-lg"), deform.Button('wants_no_membership', _(u"No")), deform.Button('back', _(u"Back"), css_class="btn-xs") ])
def accountants_login(request): """ This view lets accountants log in (using a login form). If a person is already logged in, she is forwarded to the dashboard. """ logged_in = authenticated_userid(request) LOG.info("login by %s", logged_in) if logged_in is not None: return get_dashboard_redirect(request) form = deform.Form( AccountantLogin(), buttons=[ deform.Button('submit', _(u'Submit')), deform.Button('reset', _(u'Reset')) ], ) # if the form has been used and SUBMITTED, check contents if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e_validation_failure: request.session.flash(_(u"Please note: There were errors, " "please check the form below."), 'message_above_form', allow_duplicate=False) return {'form': e_validation_failure.render()} # get user and check pw... login = appstruct['login'] password = appstruct['password'] try: checked = C3sStaff.check_password(login, password) except AttributeError: # pragma: no cover checked = False if checked: LOG.info("password check for %s: good!", login) headers = remember(request, login) LOG.info("logging in %s", login) return HTTPFound(request.route_url('dashboard'), headers=headers) else: LOG.info("password check: failed for %s.", login)
def buttons(self): return ( deform.Button('send', title=_(u"Send"), css_class='btn btn-primary'), self.button_cancel, )
def msg_form_creator(self): request = self.request _ = request.translate class MessageID(colander.SequenceSchema): msgid = colander.SchemaNode(colander.String()) class MainSchema(colander.Schema): msgid = MessageID(title="msgid", widget=widget.SequenceWidget(orderable=True)) def validator(node, appstruct): # TODO: some validation return True schema = MainSchema(validator=validator) schema = schema.bind(request=self.request) self.msg_form = deform.Form(schema, use_ajax=False, action=self.request.route_url( 'i18n_helper.pot', domain=self.domain)) self.msg_form.buttons.append( deform.Button(name='submit', title=_('i18n_pot_submit', domain='i18n_helper'))) return self.msg_form
def get_payment_form(request, counter=None): """ Return a payment form object """ valid_btn = deform.Button( name='submit', value="paid", type='submit', title=u"Valider", ) schema = ExpensePaymentSchema().bind(request=request) if request.context.__name__ == 'expense': action = request.route_path("expensesheet", id=request.context.id, _query=dict(action='status')) else: action = request.route_path("expensesheet", id=-1, _query=dict(action='status')) form = deform.Form( schema=schema, buttons=(valid_btn, ), formid="paymentform", action=action, counter=counter, ) return form
def get_form(request): session = get_session(request) session['csrf'] = get_csrf_token(session) schema = CreateArticle().bind(request=request) submit = deform.Button(name='submit', css_class='blog-form__button') return deform.Form(schema, buttons=(submit,))
def register(context, request): enabled = request.app.get_config("morpfw.new_registration.enabled", True) if not enabled: raise HTTPNotFound() schema = request.app.get_schemaextender(RegistrationForm) formschema = dc2colander.convert(schema, request=request, default_tzinfo=request.timezone()) fs = formschema() fs = fs.bind(context=context, request=request) return { "form_title": "Register", "form": deform.Form( fs, buttons=( "Register", deform.Button( "login", title="Login", type="link", value=request.relative_url("/login"), ), ), ), }
def buttons(self): return ( deform.Button('register', title=_(u"Register"), css_class='btn btn-primary'), self.button_cancel, )
def __init__(self, *args, **kwargs): super(NinsView, self).__init__(*args, **kwargs) # All buttons for adding a nin, must have a name that starts with "add". This because the POST message, sent # from the button, must trigger the "add" validation part of a nin. self.buttons = () if self.request.registry.settings.get('enable_mm_verification'): self.buttons += (deform.Button(name='add', title=_('Mina Meddelanden')),) self.buttons += (deform.Button(name='add_by_mobile', title=_('Phone subscription'), css_class='btn btn-primary'),) self.buttons += (deform.Button(name='add_by_letter', title=_('Physical letter'), css_class='btn btn-primary'),)
def buttons(self): buttons = [self.button_cancel] if self.can_vote: buttons.insert( 0, deform.Button('vote', _(u"add_vote_button", default=u"Vote"))) return buttons
def get_form(self): from forms import CreateArticle self.session = get_session(self.request) self.session['csrf'] = get_csrf_token(self.session) schema = CreateArticle().bind(request=self.request) submit = deform.Button(name='submit', css_class='blog-form__button') self.form = deform.Form(schema, buttons=(submit, )) return self.form
def __init__(self, request): self.request = request self.schema = schemas.RegisterSchema().bind(request=self.request) self.form = request.create_form(self.schema, buttons=(deform.Button(title=_('Sign up'), css_class='js-signup-btn'),), css_class='js-signup-form')
def field_assist(request, **kwargs): # add search_path to override deform templates custom_deform_templates = '%s/templates/deform' % settings.PROJECT_ROOT_PATH deform_templates = resource_filename('deform', 'templates') search_path = (custom_deform_templates, deform_templates) deform.Form.set_zpt_renderer(search_path) field_name = kwargs.get('field_name') # get previous value from field (json) field_value = request.POST.get('field_value', '') field_id = request.POST.get('field_id', field_name) module_name = request.POST.get('module_name', '') formid = request.POST.get('__formid__', '') field_name_camelcase = field_name.title().replace('_', '') field_full_classname = '{0}.field_definitions.{1}'.format( module_name, field_name_camelcase) field_definition = get_class(field_full_classname) appstruct = None field_json = None min_len_param = 1 # if previous_value allow delete the first ocurrence if field_value and field_value != '[]': min_len_param = 0 class Schema(colander.MappingSchema): data = field_definition() schema = Schema() form = deform.Form(schema, buttons=[ deform.Button('submit', _('Save'), css_class='btn btn-primary btn-large') ], use_ajax=False) form['data'].widget = deform.widget.SequenceWidget(min_len=min_len_param, orderable=True) # check if is a submit of deform form if request.method == 'POST' and formid == 'deform': controls = parse_qsl(request.body, keep_blank_values=True) try: # If all goes well, deform returns a simple python structure of # the data. You use this same structure to populate a form with # data from permanent storage appstruct = form.validate(controls) except ValidationFailure, e: # The exception contains a reference to the form object rendered = e.render() else: # form validated - create field_json with content and return to form render field_json = json.dumps(appstruct) rendered = form.render(appstruct)
def __init__(self, request): self.request = request self.schema = schemas.RegisterSchema().bind(request=self.request) self.form = request.create_form( self.schema, buttons=(deform.Button(title=_("Sign up")),), css_class="js-disable-on-submit", )
def get_filter_button(self): """ Return the definition of the filter button """ self.logger.debug("Building the filter button : %s" % self.filter_button_label) return deform.Button(title=self.filter_button_label, name='submit', type='submit', css_class='btn btn-primary')
def _group_form(request): schema = schemas.GroupSchema().bind(request=request) submit = deform.Button(title=_('Create a new group'), css_class='primary-action-btn ' 'group-form__submit-btn ' 'js-create-group-create-btn') form = deform.Form(schema, css_class='group-form__form', buttons=(submit,)) return form
def __call__(self): """Build up the schema and return the form view. """ # build the schema if it not exist if self.schema is None: if self.schema_factory is None: self.schema_factory = SettingsSchema self.schema = self.schema_factory() # append csrf token if needed if self.use_csrf_token and 'csrf_token' not in self.schema: self.schema.children.append(CSRFSchema()['csrf_token']) # enhance the schema with the given definitions for setting_obj in self.settings.settings_objs: node = colander.SchemaNode(self.colander_type(setting_obj.type)(), name=setting_obj.field_name, title=setting_obj.title, description=setting_obj.description, default=setting_obj.default) self.schema.children.append(node) # the names of the children should begin with the module name settings = get_settings() bind_values = self.settings.bind.copy() for child in self.schema.children: bind_attrs = bind_values.get(child.name, None) if child.name == 'csrf_token': continue if not child.name.startswith(self.settings.module): child.name = "%s-%s" % (self.settings.module, child.name) child.default = settings.get(child.name) if bind_attrs: for k, v in bind_attrs.iteritems(): if callable(v): v = v() setattr(child, k, v) # Build up the buttons dynamically, so we can check what setting form # was saved. save = 'save_' + self.form_id self.buttons = (deform.Button(save, _(u'Save')), deform.Button('cancel', _(u'Cancel'))) setattr(self, save + '_success', self.save_success) return super(SettingsFormView, self).__call__()
def load_init_form(self, action_node, index_node): self.d_form_data = { 'nodes': [action_node.sn, index_node.sn], 'buttons': (deform.Button('Suivant', css_class='btn-success'), ), 'mapping': { 'Suivant': None, 'action': None, 'index': None }, 'formatting': {} }
def __init__(self, request): super(RegisterController, self).__init__(request) schema = request.registry.getUtility(IRegisterSchema) self.schema = schema().bind(request=self.request) sign_up_button = deform.Button(name="sign_up", title="Sign up with email", css_class="btn-lg btn-block") form = request.registry.getUtility(IRegisterForm) self.form = form(self.schema, buttons=(sign_up_button, ))
def __init__(self, context, request: Request): self.request = request self.context = context _ = request.translate self.helper = request.registry['i18n_helper'] # Select Domain FORM self.pot_dir = self.helper.locale_dir domains_choices = [(pot.rsplit('.',maxsplit = 1)[0],pot.rsplit('.',maxsplit = 1)[0]) for pot in os.listdir(self.pot_dir) if pot.endswith('.pot')] class SelectDomain(colander.Schema): select_domain = colander.SchemaNode(colander.String(), widget=deform.widget.SelectWidget(values=domains_choices), title=_("i18n_select_domain", domain='i18n_helper')) class NewDomain(colander.Schema): new_domain = colander.SchemaNode(colander.String(), title=_("i18n_new_domain", domain='i18n_helper')) def validator(node, appstruct): return True schema = NewDomain(validator=validator) schema = schema.bind(request=self.request) self.new_domain_form = deform.Form(schema, use_ajax=False, action=self.request.route_url('i18n_helper.domain')) self.new_domain_form.buttons.append(deform.Button(name='submit', title=_('i18n_new_domain_submit', domain='i18n_helper'))) schema = SelectDomain(validator=validator) schema = schema.bind(request=self.request) self.select_domain_form = deform.Form(schema, use_ajax=False, action=self.request.route_url('i18n_helper.domain')) self.select_domain_form.buttons.append(deform.Button(name='submit', title=_('i18n_select_domain_submit', domain='i18n_helper')))
class BaseFormView(FormView): """ A basic view for forms with save and cancel buttons. """ form_class = Form buttons = (deform.Button('save', _(u'Save')), deform.Button('cancel', _(u'Cancel'))) success_message = _(u"Your changes have been saved.") success_url = None schema_factory = None use_csrf_token = True add_template_vars = () def __init__(self, context, request, **kwargs): self.context = context self.request = request self.__dict__.update(kwargs) def __call__(self): if self.schema_factory is not None: self.schema = self.schema_factory() if self.use_csrf_token and 'csrf_token' not in self.schema: self.schema.children.append(CSRFSchema()['csrf_token']) result = super(BaseFormView, self).__call__() if isinstance(result, dict): result.update(self.more_template_vars()) return result def cancel_success(self, appstruct): location = self.request.resource_url(self.context) return HTTPFound(location=location) cancel_failure = cancel_success def more_template_vars(self): result = {} for name in self.add_template_vars: result[name] = getattr(self, name) return result
class MobilesView(BaseFormView): """ Change user mobiles * GET = Rendering template * POST = Creating or modifing mobiles data, return status and flash message """ schema = Mobile() route = 'mobiles' buttons = (deform.Button(name='add', title=_('Add')), ) bootstrap_form_style = 'form-inline' def appstruct(self): return {} def get_template_context(self): context = super(MobilesView, self).get_template_context() context.update({ 'mobiles': self.user.phone_numbers.to_list(), }) return context def add_success(self, mobileform): mobile_number = self.schema.serialize(mobileform)['mobile'] mobile_number = normalize_to_e_164(self.request, mobile_number) mobile = PhoneNumber( data={ 'number': mobile_number, 'verified': False, 'primary': False, 'created_ts': datetime.utcnow() }) self.user = get_session_user(self.request) self.user.phone_numbers.add(mobile) try: self.context.save_dashboard_user(self.user) except UserOutOfSync: self.sync_user() else: send_verification_code(self.request, self.user, mobile_number) self.request.session.flash(_('Changes saved'), queue='forms') msg = _( 'A confirmation code has been sent to your mobile phone. ' 'Please click on the "Pending confirmation" link below and enter your confirmation code.' ) msg = get_localizer(self.request).translate(msg) self.request.session.flash(msg, queue='forms')
def __init__(self, request): self.request = request self.schema = schemas.group_schema(autofocus_name=True).bind( request=self.request) submit = deform.Button(title=_('Create group'), css_class='primary-action-btn ' 'group-form__submit-btn ' 'js-create-group-create-btn') self.form = request.create_form(self.schema, css_class='group-form__form', buttons=(submit, ))
def create_form(self): _ = self.request.translate po_entries = {entry.msgid: entry.msgstr for entry in self.po} class PoEntry(colander.Schema): def after_bind(self, schema, kwargs): for entry in po_entries: self[entry] = colander.SchemaNode( colander.String(), title=entry, missing='', default=po_entries.get(entry), # description=po_entries.get(entry) ) class MainSchema(colander.Schema): msgid = PoEntry() def validator(node, appstruct): return True schema = MainSchema(validator=validator) schema = schema.bind(request=self.request) self.form = deform.Form(schema, use_ajax=False, action=self.request.route_url( 'i18n_helper.po', lang=self.lang, domain=self.domain)) self.form.buttons.append( deform.Button(name='submit', title=_('i18n_translate_submit', domain='i18n_helper'))) self.form.buttons.append( deform.Button(name='reload', title=_('i18n_translate_reload', domain='i18n_helper'))) return self.form