class Three(Layouts): def __init__(self, context, request): super(Three, self).__init__(context, request) schema = GuestBookSchema().bind() button = Button(name="submit", title="Submit") self.form = Form(schema, buttons=(button,)) @view_config(request_method="GET") def get(self): return { 'form': self.form.render(), 'js': self.form.get_widget_resources()['js'], 'css': self.form.get_widget_resources()['css'], 'comments': comments, } @view_config(request_method="POST", request_param="submit") def post(self): controls = self.request.POST.items() try: appstruct = self.form.validate(controls) except ValidationFailure as e: return { 'form': e.render(), 'js': self.form.get_widget_resources()['js'], 'css': self.form.get_widget_resources()['css'], 'comments': comments, } # So, obviously, in real life this would go in a database, # but I CBA, so I'm using a global value as my DB comments.append(appstruct) return {'form':'', 'comments':comments}
def do_text_section_view(self): """ Text section, should be included in the regular do view in time. """ survey = self.context.__parent__ survey.check_open() participant_uid = self.request.params.get('uid') if not participant_uid in survey.tickets: raise Forbidden("Invalid ticket") schema = colander.Schema() next_section = self._next_section() previous_section = self._previous_section() buttons = [self.buttons['next']] if previous_section: buttons.insert(0, self.buttons['previous']) form = Form(schema, buttons=buttons) self.response['form_resources'] = form.get_widget_resources() post = self.request.POST if 'next' in post: if next_section: url = self.request.resource_url(next_section, 'do', query = {'uid': participant_uid}) else: url = self.request.resource_url(survey, 'finished') return HTTPFound(location = url) if 'previous' in post: url = self.request.resource_url(previous_section, 'do', query = {'uid': participant_uid}) return HTTPFound(location = url) self.response['form'] = form.render() return self.response
def show_dummy_form_view(self): schema = colander.Schema() self.context.append_questions_to_schema(schema, self.request) form = Form(schema) self.response['form_resources'] = form.get_widget_resources() self.response['dummy_form'] = form.render() return self.response
def participants_view(self): """ Overview of participants. """ self.response['participants'] = participants = self.context.get_participants_data() not_finished = [x for x in participants if x['finished']<100] self.response['not_finished'] = not_finished self.response['closed_survey'] = self._closed_survey(self.context) schema = createSchema(self.context.schemas['reminder']) schema = schema.bind(context = self.context, request = self.request) form = Form(schema, buttons=(self.buttons['send'],)) self.response['form_resources'] = form.get_widget_resources() post = self.request.POST if 'send' in post: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response for participant in not_finished: # a participant with less then 100% completion will receive the invite ticket again with specified message ticket_uid = participant['uid'] email = self.context.tickets[ticket_uid] self.context.send_invitation_email(self.request, email, ticket_uid, appstruct['subject'], appstruct['message']) self.add_flash_message(_(u"Reminder has been sent"))
def start_survey_view(self): """ This view askes the participant which language it wants and redirects to the first section. This starts the survey for this participant. """ try: self.context.check_open() except SurveyUnavailableError as e: self.add_flash_message(e.msg) url = self.request.resource_url(self.context, 'unavailable') return HTTPFound(location=url) selected_language = None available_languages = self.context.get_available_languages() schema = createSchema(self.context.schemas['language']) schema = schema.bind(languages = available_languages, context = self.context, request = self.request) form = Form(schema, buttons=(self.buttons['save'],)) self.response['form_resources'] = form.get_widget_resources() post = self.request.POST if 'save' in post: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response selected_language = appstruct['selected_language']
def view_user(request): if 'hash' not in request.matchdict or not request.matchdict['hash']: return {'form': None} hash = request.matchdict['hash'] geo_form_schema = _get_schema(request) renderer = _get_renderer(geo_form_schema.templates_user) form = Form(geo_form_schema.schema_user, renderer=renderer) _set_form_widget(form, geo_form_schema.schema_user, 'form_view_user') _populate_widgets(form.schema, DBSession, request) hash_field = getattr( geo_form_schema.model, geo_form_schema.hash_column_name) try: obj = DBSession \ .query(geo_form_schema.model) \ .filter(hash_field == hash) \ .one() except NoResultFound: return {'form': None} rendered = form.render(geo_form_schema.schema_user.dictify(obj), readonly=True, request=request) return { 'form': rendered, 'schema': geo_form_schema, 'deform_dependencies': form.get_widget_resources()}
def variant(self): question_name = self.request.GET.get('question_name', None) globalquestions = self.root['questions'] if question_name not in globalquestions: self.add_flash_message(_(u"Invalid question name.")) url = self.request.resource_url(self.context) return HTTPFound(location=url) question = globalquestions[question_name] schema = createSchema(question.schemas['translate']) schema.title = _(u"Edit question variant for this organisation") schema = schema.bind(context = question, request = self.request) # add default locale description = question.get_original_title() descriptions = question.get_question_text() self.trans_util.add_translation_schema(schema['question_text'], self.trans_util.default_locale_name, description=description) self.trans_util.add_translations_schema(schema['question_text'], self.context, descriptions=descriptions, only_with_description=True) form = Form(schema, action = self.request.url, buttons=(self.buttons['save'], self.buttons['cancel'])) self.response['form_resources'] = form.get_widget_resources() if 'save' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response for (lang, value) in appstruct['question_text'].items(): self.context.set_variant(question_name, lang, value) url = self.request.resource_url(self.context, 'variants') return HTTPFound(location = url)
def do_survey_section_view(self): """ Where participants go to tell us about their life... """ survey = self.context.__parent__ survey.check_open() participant_uid = self.request.params.get('uid') if not participant_uid in survey.tickets: raise Forbidden("Invalid ticket") schema = colander.Schema() self.context.append_questions_to_schema(schema, self.request) next_section = self._next_section() previous_section = self._previous_section() buttons = [self.buttons['next']] if previous_section: buttons.insert(0, self.buttons['previous']) form = Form(schema, buttons=buttons) self.response['form_resources'] = form.get_widget_resources() post = self.request.POST if 'next' in post: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response self.context.update_question_responses(participant_uid, appstruct) if next_section: url = self.request.resource_url(next_section, 'do', query = {'uid': participant_uid}) else: url = self.request.resource_url(survey, 'finished') return HTTPFound(location=url)
def survey_view(self): if self.userid: return HTTPFound(location = self.request.resource_url(self.context, 'view')) try: self.context.check_open() self.response['survey_open'] = True except SurveyUnavailableError: self.response['survey_open'] = False self.response['allow_anonymous_to_participate'] = self.context.get_field_value('allow_anonymous_to_participate', False) if self.response['survey_open']: schema = createSchema('ParticipantControlsSchema') schema = schema.bind(context = self.context, request = self.request) form = Form(schema, buttons=(self.buttons['send'],)) self.response['form_resources'] = form.get_widget_resources() if 'send' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response if appstruct['participant_actions'] == u"send_anon_invitation" and self.response['allow_anonymous_to_participate']: self.send_invitation(appstruct['email']) if appstruct['participant_actions'] == u"start_anon" and self.context.get_field_value('allow_anonymous_to_start', False): if appstruct['email'] in self.context.tickets.values(): #Check if participant actually started the survey, or was just invited #FIXME: We're looping twice - we should use a reverse key registry instead. for (participant_uid, email) in self.context.tickets.items(): #This will of course be true, since we already know email is in there. if appstruct['email'] == email: if self.root['participants'].participant_by_ids(self.context.__name__, participant_uid): #Abort if survey data founds msg = _(u"email_already_used_notice", default = u"Your email address has already been used within this survey. " u"If you need to change your replies, use the access link provided when you started " u"the survey, or resend the link by using the form below.") self.add_flash_message(msg) return HTTPFound(location = self.request.resource_url(self.context)) invitation_uid = self.context.create_ticket(appstruct['email']) access_link = self.request.resource_url(self.context, 'do', query = {'uid': invitation_uid}) msg = _(u"participant_unverified_link_notice", default = u"Important! Since you're starting this survey without a verified email, please copy this " u"link in case you need to access the survey again: ${link}", mapping = {'link': access_link}) self.add_flash_message(msg) return HTTPFound(location = access_link) if appstruct['participant_actions'] == u"resend_access": if appstruct['email'] not in self.context.tickets.values() and not self.response['allow_anonymous_to_participate']: msg = _(u"cant_resend_access_error", default = u"Unable to resend access code - your email wasn't found among the invited.") self.add_flash_message(msg) return HTTPFound(location = self.request.resource_url(self.context)) self.send_invitation(appstruct['email']) self.response['form'] = form.render()
def admin_view(self): schema = createSchema(self.context.schemas['edit']) schema = schema.bind(context = self.context, request = self.request) appstruct = self.context.get_field_appstruct(schema) form = Form(schema, buttons=()) self.response['form_resources'] = form.get_widget_resources() self.response['form'] = form.render(readonly = True, appstruct = appstruct) self.response['listing'] = self.listing_sniplet() return self.response
def show_dummy_text_view(self): schema = createSchema(self.context.schemas['edit']) form = Form(schema) lang = self.get_lang() appstruct = {'title': self.context.get_title(lang = lang), 'description': self.context.get_description(lang = lang)} self.response['form_resources'] = form.get_widget_resources() self.response['dummy_form'] = form.render(readonly = True, appstruct = appstruct) return self.response
def get_widget_css_urls(self, request: Request, form: Form): """Generate JS and CSS tags for a widget. For demo purposes only - you might have something specific to your application here. See http://docs.pylonsproject.org/projects/deform/en/latest/widget.html#the-high-level-deform-field-get-widget-resources-method """ resources = form.get_widget_resources() css_resources = resources['css'] css_links = [request.static_url(r) for r in css_resources] return css_links
def get_widget_css_urls(self, request: Request, form: Form): """Generate JS and CSS tags for a widget. For demo purposes only - you might have something specific to your application here. See http://docs.pylonsproject.org/projects/deform/en/latest/widget.html#the-high-level-deform-field-get-widget-resources-method """ resources = form.get_widget_resources() css_resources = resources['css'] css_links = [request.static_url(r) for r in css_resources] return css_links
def view(request): id_ = request.matchdict['id'] geo_form_schema = _get_schema(request) renderer = _get_renderer(geo_form_schema.templates_admin) form = Form(geo_form_schema.schema_admin, buttons=('submit',), renderer=renderer) obj = DBSession.query(geo_form_schema.model).get(id_) rendered = form.render(geo_form_schema.schema_admin.dictify(obj), readonly=True) return { 'form': rendered, 'schema': geo_form_schema, 'deform_dependencies': form.get_widget_resources()}
def view_admin(request): id_ = request.matchdict['id'] geo_form_schema = _get_schema(request) renderer = _get_renderer(geo_form_schema.templates_admin) form = Form(geo_form_schema.schema_admin, buttons=('submit',), renderer=renderer) obj = DBSession.query(geo_form_schema.model).get(id_) rendered = form.render(geo_form_schema.schema_admin.dictify(obj), readonly=True, request=request) return { 'form': rendered, 'schema': geo_form_schema, 'deform_dependencies': form.get_widget_resources()}
def form_view(request): schema = EditMenuItems() myform = Form(schema, buttons=('submit',)) reqt = myform.get_widget_resources(myform.get_widget_requirements()) if 'submit' in request.POST: controls = request.POST.items() try: myform.validate(controls) except ValidationFailure as e: return {'form':e.render()} return {'form':'OK'} return {'form': myform.render(), 'project': 'poop', 'css': reqt['css'], 'js': reqt['js']}
def change_password_view(self): """ Change password view. """ schema = createSchema(self.context.schemas['change_password']) schema = schema.bind(context = self.context, request = self.request) form = Form(schema, buttons=(self.buttons['save'],)) self.response['form_resources'] = form.get_widget_resources() if 'save' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response self.context.set_field_appstruct(appstruct) url = self.request.resource_url(self.context) return HTTPFound(location = url)
def show(self, form): # re-validate form, it is possible to be changed appstruct = {} controls = list(self.request.POST.items()) if controls: try: appstruct = form.validate(controls) except deform.exception.ValidationFailure as e: return self.failure(e) schema = form.schema # now add new schemas, at the end of all others add_component = appstruct.pop('pipeline_components', None) if add_component: p = pipeline_registry[add_component] s = p.schema(name=rand(10), title=p.title,) schema.add(s) # move pipeline_components to the bottom w = schema.__delitem__('pipeline_components') schema.add(w) # try to build a preview, if possible if appstruct.get('column'): pipeline = self.pipeline_from_schema(schema, appstruct) pstruct = self.request.create_corpus_pipeline_struct = { 'file_name': self.document, 'text_column': appstruct['column'], 'pipeline': pipeline, 'preview_mode': True } content_stream = build_pipeline(**pstruct) self.preview = islice(content_stream, 0, self.preview_size) form = Form(schema, buttons=self.buttons, renderer=deform_renderer, **dict(self.form_options)) reqts = form.get_widget_resources() return { 'form': form.render(appstruct), 'css_links': reqts['css'], 'js_links': reqts['js'], }
def reorder_folder(self): post = self.request.POST ui_sortable.need() if 'cancel' in self.request.POST: url = self.request.resource_url(self.context) return HTTPFound(location = url) if 'save' in post: controls = self.request.POST.items() items = [] for (k, v) in controls: if k == 'items': items.append(v) self.context.order = items self.add_flash_message(_('Order updated')) form = Form(colander.Schema()) self.response['form_resources'] = form.get_widget_resources() self.response['dummy_form'] = form.render() return self.response
def form_view(request): schema = UserSchema() myform = Form(schema, buttons=('submit', )) template_values = {} template_values.update(myform.get_widget_resources()) if 'submit' in request.POST: controls = request.POST.items() try: myform.validate(controls) except ValidationFailure as e: template_values['form'] = e.render() else: template_values['form'] = 'OK' return template_values template_values['form'] = myform.render() return template_values
def search(context, request): search_form = Form(Search(), action='search', buttons=('search',), css_class='well') if 'search' in request.POST: try: appstruct = search_form.validate(request.POST.items()) except ValidationFailure, e: return {'context': context, 'form':e.render(), 'resources' : search_form.get_widget_resources()} search_results = context.search(appstruct['query'], appstruct['after_date']) results = [] for line in search_results: line[2].anchorlink = resource_url(line[0], request, anchor = str(line[1])) line[2].date = line[0].date line[2].chan = line[0].__parent__.__name__ results.append(line[2]) return dict(context=context, results=results, query=appstruct['query'])
def form_view(request): schema = EditMenuItems() myform = Form(schema, buttons=('submit', )) reqt = myform.get_widget_resources(myform.get_widget_requirements()) if 'submit' in request.POST: controls = request.POST.items() try: myform.validate(controls) except ValidationFailure as e: return {'form': e.render()} return {'form': 'OK'} return { 'form': myform.render(), 'project': 'poop', 'css': reqt['css'], 'js': reqt['js'] }
def translate_question_view(self): lang = self.request.GET['lang'] schema = createSchema(self.context.schemas['translate']) schema = schema.bind(context = self.context, request = self.request) self.trans_util.add_translation_schema(schema['question_text'], lang) form = Form(schema, buttons=(self.buttons['save'], self.buttons['cancel'])) self.response['form_resources'] = form.get_widget_resources() if self.request.method == 'POST': if 'save' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response for (lang, value) in appstruct['question_text'].items(): self.context.set_question_text_lang(value, lang) url = unquote(self.request.GET['came_from']) return HTTPFound(location = url)
def questions_view(self): """ This view is for any IQuestions context, both the global one and the local one + the Organisation objects 'variants' view. """ schema = createSchema('QuestionSearchSchema').bind(context = self.context, request = self.request) form = Form(schema, buttons = (), formid = 'tag_select', action = 'javascript:') self.response['form_resources'] = form.get_widget_resources() self.response['tag_form'] = form.render() #Get questions, sorted - behaves differently for variants! if IOrganisation.providedBy(self.context): questions = self.root['questions'].values() else: questions = self.context.values() self.response['questions'] = sorted(questions, key = lambda q: q.get_field_value('title').lower()) self.response['is_org'] = IOrganisation.providedBy(self.context) self.response['show_edit_variants'] = self.response['is_org'] and \ security.context_has_permission(self.context, security.MANAGE_SURVEY, self.userid) self.response['show_edit'] = IQuestions.providedBy(self.context) and \ security.context_has_permission(self.context, security.EDIT, self.userid) or False return self.response
def get(self): self.loggerRoot.info("start autoform demo page get.") #test time code. #import time #time.sleep(10) #myform = deform.Form(schema, buttons=('submit',)) #form = myform.render() schema = MySchema() myform = Form(schema, buttons=('submit', )) template_values = {} template_values.update(myform.get_widget_resources()) #if 'submit' in request.POST: # controls = request.POST.items() # try: # myform.validate(controls) # except ValidationFailure as e: # template_values['form'] = e.render() # else: # template_values['form'] = 'OK' # return template_values template_values['form'] = myform #template_values['form'] = myform.render() if 'css' in template_values: pass else: template_values['css'] = None if 'js' in template_values: pass else: template_values['js'] = None self.render("deformdemo/example.zpt", css=template_values['css'], js=template_values['js'], form=template_values['form'])
def admin_view(self): schema = Schema() schema.add(self.context.question_schema_node('dummy', lang = self.get_lang(), context = self.context)) form = Form(schema) self.response['form_resources'] = form.get_widget_resources() self.response['dummy_form'] = form.render() return self.response