def update_ticket(self): project = self.context.project ticket = self.context.ticket form = Form(self.request, schema=s.TicketSchema, obj=ticket) if form.validate(): form.bind(ticket) return HTTPFound(location=h.ticket_url(self.request, ticket))
def edit(request): """customer edit """ id = request.matchdict['id'] dbsession = DBSession() customer = dbsession.query(Customer).filter_by(id=id).one() print customer address = dbsession.query(Address).filter_by(user_id=id).one() if customer is None or address is None: request.session.flash("error;Customer not found!") return HTTPFound(location=request.route_url("customer_list")) generalForm = Form(request, schema=CustomerForm, obj=customer) locationForm = Form(request, schema=LocationForm, obj=address) if "general_submitted" in request.POST and generalForm.validate(): generalForm.bind(customer) dbsession.add(customer) request.session.flash("success; Successful call to update customer") if "location_submitted" in request.POST: locationForm.bind(address) dbsession.add(address) request.session.flash("success; Successful call to update location") action_url = request.route_url("customer_edit", id=id) return dict(generalForm=FormRenderer(generalForm), locationForm=FormRenderer(locationForm), action_url=action_url)
def concept_save_view(request): if "concept" in request.POST: form = Form(request, schema=ConceptAnswersSchema()) if form.validate(): answers = [] concept_answers = form.bind(models.ConceptAnswer()) concept = concept_answers.concept concept_answers = concept_answers.concept_answer for concept_answer in concept_answers: answer = models.ConceptAnswer() answer.concept = concept answer.concept_answer = concept_answer answers.append(answer) with transaction.manager: models.DBSession.add_all(answers) else: print form.all_errors() print "NOT VALIDATED" return "I saw it" form = Form(request, schema=ConceptSchema()) concept_model = None if form.validate(): concept = form.bind(models.Concept()) #with transaction.manager: # models.DBSession.add(concept) concept_model = models.DBSession.merge(concept) models.DBSession.flush() return HTTPFound(request.route_url("concept_edit_page", page="Concepts",\ concept_id=concept_model.id)) else: print "Failed"
def password_edit_view(request): """ Render the change password form page. Seek the database for the user datas based on user_id used in the route. If the user did not exist then add an error flash message and redirect to the user list. If the user exist then render an empty password form. If the form is validated then change the user password in the database and add success flash message. If the form is not valid, then display again the form with validation errors. :param request: a ``pyramid.request`` object """ _ = request.translate user_id = request.matchdict['user_id'] user = AuthUser.get_by_id(user_id) if not user: request.session.flash(_(u"This user did not exist!"), 'error') return HTTPFound(location=request.route_path('tools.user_list')) form = Form(request, schema=UserPasswordForm, obj=user) if 'form_submitted' in request.params and form.validate(): form.bind(user) DBSession.add(user) request.session.flash(_(u"Password updated."), 'success') return HTTPFound(location=request.route_path('tools.user_list')) return dict(renderer=FormRenderer(form))
def index(self): tenant = None errors = None success = None tenantForm = None contactForm = None try: tenantService = TenantService() tenant = tenantService.GetTenantDetails(self.TenantId) tenantForm = Form(self.request, schema=TenantSchema, obj=tenant) contactForm = vForm( request=self.request, prefix="tenantcontact-", schema=ContactSchema, obj=tenant.Contacts[0] ) valid = tenantForm.validate() valid = contactForm.validate() and valid if valid: tenantForm.bind(tenant) contactForm.bind(tenant.Contacts[0]) tenant.UpdatedBy = self.UserId tenant.UpdatedOn = datetime.utcnow() if tenantService.SaveTenant(tenant): success = "Company details saved successfully!" else: errors = "Error while saving Company details. Please try later." except Exception, e: log.info(e) errors = e.message
def login(self): if self.logged_in: self.request.session.flash('You are already connected!', queue='notice') return HTTPFound( location=self.request.route_url('home') ) self.c.pagename = 'Login' self.c.active_header_nav = 'tools' self.c.active_footer_nav = 'tools-login' params = self.request.params form = Form(self.request, schema=LoginForm, obj=params) if form.validate(): form.bind(params) #clear the cache for user User.by_username(params.get('username'), invalidate=True) user = User.by_username(params.get('username'), cache=None) if user: password = params.get('password') if user.password == User.pass_crypt(password)\ and user.status == 1: user.last_login_date = sa.func.now() self.request.session.flash(u'Welcome back %s !' % user.username, queue='success') headers = security.remember(self.request, user.username) return HTTPFound(location=self.request.route_url('home'), headers=headers) self.request.session.flash(u'Wrong username or password!', queue='notice') return { 'item': params, 'form': FormRenderer(form) }
def edit(txt, request): if not request.usr: return HTTPForbidden() form = Form(request, TxtSchema, obj=txt) if form.validate(): form.bind(txt) request.bus.fire(TxtEditedEvent(txt=txt)) return HTTPFound(location=request.route_url('txt.view', txt_id=txt.id)) return {'form': FormRenderer(form), 'txt': txt}
def usr_edit(request): form = Form(request, EditSchema(usr=request.usr), obj=request.usr) if form.validate(): form.bind(request.usr) DBSession.add(request.usr) request.session.flash(('success', u'Saved changes to profile.')) return HTTPFound( location=request.route_url('usr.view') ) return {'usr': request.usr, 'form': FormRenderer(form)}
def manage(self): errors = None if self.request.method == 'POST': sid = self.request.params.get('sid', None) else: sid = self.request.matchdict.get('sid', None) try: if sid: #edit model = supplierService.GetSupplier(sid, self.TenantId) if not model: return HTTPFound(location='/suppliers/index') form = Form(self.request, schema=SupplierSchema, obj=model) cntform = vForm(prefix='suppliercontact-', request=self.request, schema=ContactSchema, obj=model.Contacts[0]) valid = form.validate() valid = cntform.validate() and valid if valid: form.bind(model) cntform.bind(model.Contacts[0]) model.UpdatedBy = self.UserId model.Status = True if supplierService.SaveSupplier(model): return HTTPFound(location='/suppliers/index') else: errors = 'Unable to add suppliers details!' else: #add model = Supplier() form = Form(self.request, schema=SupplierSchema, defaults={}) cntform = vForm(prefix='suppliercontact-', request=self.request, schema=ContactSchema, defaults={}) valid = form.validate() valid = cntform.validate() and valid if valid: model = form.bind(Supplier()) contact = cntform.bind(SupplierContactDetails()) model.Contacts.append(contact) model.TenantId = self.TenantId model.CreatedBy = self.UserId model.Status = True if supplierService.AddSupplier(model): return HTTPFound(location='/suppliers/index') else: errors = 'Unable to save suppliers details!' except Exception, e: errors = str(e)
def save(self): instance_id = self.request.params.get('instance_id') query = models.DBSession.query(models.InstanceModel) instance = query.filter_by(instance_id=instance_id).first() if instance is None: raise exc.HTTPNotFound() form = Form(self.request, schema=self.schema, obj=instance) if not form.validate(): raise exc.HTTPBadRequest() form.bind(instance) return {"result": "ok"}
def usr_passwd(request): form = Form(request, PasswdSchema) if form.validate(): form.bind(request.usr) DBSession.add(request.usr) request.session.flash(('success', u'Password successfully changed.')) return HTTPFound( location=request.route_url('usr.view') ) return {'usr': request.usr, 'form': FormRenderer(form)}
def addpurchaselineitem(self): purchaseId = self.request.params.get('pid', None) supplierId = self.request.params.get('SupplierId', None) if purchaseId and supplierId: model = None productId = self.request.params.get('ProductId', None) quantity = float(self.request.params.get('Quantity', 0.0)) taxAmount = float(self.request.params.get('TaxAmount', 0.0)) try: if productId: model = stockService.GetProduct(productId, self.TenantId) if not model: model = Product() pForm = Form(self.request, schema=ProductSchema, obj=model) if pForm.validate(): pForm.bind(model) model.SupplierId = supplierId model.TenantId = self.TenantId model.Status = True if model.Id: model.UpdatedBy = self.UserId stockService.SaveProduct(model) else: model.CreatedBy = self.UserId stockService.AddProduct(model) litem = PurchaseLineItem() litem.PurchaseId = purchaseId litem.ProductId = model.Id litem.Name = model.Name litem.Barcode = model.Barcode litem.MRP = model.MRP litem.Tax = taxAmount litem.BuyPrice = model.BuyPrice litem.Discount = model.Discount litem.Quantity = quantity result = stockService.AddPurchaseLineItem(litem, self.TenantId) if result: return dict(status=True, id=litem.Id, message="Item added successfully!") else: DBSession.rollback() else: log.info('pForm validate failed : %s!' % (pForm.all_errors())) return dict(status=False, message=pForm.all_errors()) except Exception, e: log.debug(e) DBSession.rollback() return dict(status=False, message=e.message)
def managepurchase(self): errors = None model = None form = None productmodel = Product() pForm = Form(self.request, schema=ProductSchema, defaults=productmodel.toDict()) log.info(self.request.method) if self.request.method == 'GET': pid = self.request.matchdict.get('pid', None) else: pid = self.request.params.get('pid', None) lstSuppliers = self.GetSuppliers() try: if pid: model = stockService.GetPurchase(pid, self.TenantId) if not model: return HTTPFound(location='/stock/purchases') form = Form(self.request, schema=PurchaseSchema, obj=model) if form.validate(): form.bind(model) model.TenantId = self.TenantId model.UpdatedBy = self.UserId model.Status = True if stockService.SavePurchase(model): return HTTPFound(location=self.request.route_url('purchases')) else: errors = 'Unable to save purchase details!' else: model = Purchase() form = Form(self.request, schema=PurchaseSchema, defaults=model.toDict()) if form.validate(): model = form.bind(Purchase()) model.TenantId = self.TenantId model.CreatedBy = self.UserId model.Status = True if stockService.AddPurchase(model): return HTTPFound(location=self.request.route_url('editpurchase',pid=model.Id)) else: errors = 'Unable to save purchase details!' except Exception, e: errors = str(e) log.debug(e) DBSession.rollback()
def signup_post(request): dbsession = DBSession() settings = request.registry.settings form = Form(request, schema=schemas.Signup, obj=User()) if request.POST and form.validate(): if not validate_csrf(request): return HTTPUnauthorized("Not authorized") user = form.bind(User()) user.username = get_username(user.name, dbsession) user.password = func.sha1(user.password) cookie = facebook.get_user_from_cookie( request.cookies, settings["facebook.app.id"], settings["facebook.app.secret"] ) if cookie: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") user.fb_id = profile["id"] user.fb_profile_url = profile["link"] user.fb_access_token = cookie["access_token"] try: dbsession.add(user) dbsession.commit() headers = remember_me_header(request, user.email) redirect_url = route_url("create_profile", request) request.response_headerlist = headers return {"status": 1, "url": redirect_url} except IntegrityError: return {"errors": {"form": "Invalid Information"}} return {"errors": form.errors}
def view_task(request): story_id = request.matchdict['story_id'] story = DBSession.query(Story).get(story_id) task_id = request.matchdict['task_id'] task = DBSession.query(Task).get(task_id) times_spent = DBSession.query(TimeSpent.duration).filter( TimeSpent.task_id==task_id).all() form = Form(request, schema=TimeSpentSchema()) if request.method == 'POST' and form.validate(): time_spent = form.bind(TimeSpent()) time_spent.task_id = task_id time_spent.task = task DBSession.add(time_spent) DBSession.flush() return HTTPFound(location='/story/%s/task/%s' % (story_id, task_id)) return { 'story': story, 'story_id': story_id, 'task': task, 'task_id': task_id, 'times_spent': times_spent, 'renderer': FormRenderer(form), 'form': form, 'total_time_spent': str(sum_time_spent(times_spent)), 'user': get_user(request), }
def login(request): message = None form = Form(request, schema=UserSchema()) if request.method == 'POST' and form.validate(): username = request.params['username'] password = request.params['password'] password_again = request.params['password_again'] if bool(password_again): if password == password_again: user = form.bind(User()) DBSession.add(user) DBSession.flush() user_id = user.id headers = remember(request, user.id) return HTTPFound(location='/', headers=headers) else: message = 'Passwords do not match.' else: user = DBSession.query(User).filter(User.username==username).first() if user and user.password == password: headers = remember(request, user.id) return HTTPFound(location='/', headers=headers) else: message = 'Username or password is incorrect.' return { 'message': message, 'form': form, 'renderer': FormRenderer(form), 'user': get_user(request), }
def edit(request): item_id = request.matchdict['item_id'] item = session.query(Note).get(item_id) form = Form(request, schema=NoteSchema, obj=item) if form.validate(): form.bind(item) # persist model somewhere... return HTTPFound(location='/') return dict(item=item, form=FormRenderer(form))
def add(txt, request): if not request.usr: return HTTPForbidden() id = h.get_default_tex_header_id(request) obj = h.Struct(**{ 'tex_header_id': id, }) if id else None form = Form(request, AnnotationSchema, obj=obj) if form.validate(): annotation = form.bind( Annotation(creator=request.usr), exclude=['next', 'courser_position', 'focused_element'] ) annotation.txts.append(txt) request.bus.fire(AnnotationCreatedEvent(annotation=annotation)) if form.data['next'] == 'view': location = request.route_url('annotation.view', txt_id=txt.id, annotation_id=annotation.id) elif form.data['next'] == 'edit': location = request.route_url('annotation.edit', annotation_id=annotation.id, _query={ 'courser_position': form.data['courser_position'], 'focused_element': form.data['focused_element'] } ) else: location = request.route_url('txt.view', txt_id=txt.id) return HTTPFound(location=location) return {'form': FormRenderer(form), 'txt': txt}
def signup(request): form = Form(request, schema=SignupSchema()) if form.validate(): user = form.bind(User()) DBSession.add(user) request.session.flash(u'Now you can sign in', 'success') return HTTPFound(location=request.route_url('signin')) return _response_dict(request, renderer=FormRenderer(form))
def visit_view(request): if not request.is_xhr: return {"Message": "Invalid request"} form = Form(request, schema=VisitSchema()) if form.validate(): visit = form.bind(Visit()) with transaction.manager: DBSession.add(visit)
def create_pad(request): form = Form(request, schema=PadSchema()) if form.validate(): pad = form.bind(Pad()) pad.user = get_current_user(request) DBSession.add(pad) request.session.flash(u'Pad is successfully created', 'success') return HTTPFound(location=request.route_url('notes')) return _response_dict(request, renderer=FormRenderer(form), pad=False)
def concept_datatype_save_view(request): print "Reached ME!!!" if "concept_datatype" in request.POST: form = Form(request, schema=ConceptDataTypeSchema) if form.validate(): concept_datatype = form.bind(models.ConceptDataType()) with transaction.manager: models.DBSession.merge(concept_datatype) return HTTPFound(request.route_url("concept_datatype_list_page", page= "Concept Data Type", headings= concept_headings, items= concept_datatypes()))
def form_save(request): form_id = request.params["form", None] if form_id: form = Form(request, schema=FormConceptSchema()) if form.validate(): concepts = [] form_concepts = form.bind(models.FormConcept()) form_id = form_concepts.form form_concepts = form_concepts.concepts for form_concept in form_concepts: concept = models.FormConcept() concept.form = form_id concept.concept = form_concept concepts.append(concept) with transaction.manager: models.DBSession.add_all(concepts) return HTTPFound(request.route_url("form_list", page="List of Forms", \ items=get_forms(), headings=headings)) else: print "validation_failed" print form.all_errors() print request.params return else: print "We are dealing with a new form" form = Form(request, schema=FormSchema) if form.validate(): form_model = form.bind(models.Form()) #with transaction.manager: # models.DBSession.merge(form_model) form_model = models.DBSession.merge(form_model) models.DBSession.flush() print form_model.id return HTTPFound(request.route_url(\ "form_edit_page", page="Forms", form_id=form_model.id,\ form=FormRenderer(form))) else: print "validation Failed!!!"
def test_is_validated_with_specified_params(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" form = Form(request, SimpleFESchema) form.validate(params={'name' : 'foo'}) obj = form.bind(SimpleObj()) self.assert_(obj.name == 'foo')
def test_bind_with_exclude(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" request.POST["name"] = "test" form = Form(request, SimpleFESchema) form.validate() obj = form.bind(SimpleObj(), exclude=["name"]) self.assertTrue(obj.name == None)
def edit(request): """country edit """ id = request.matchdict['id'] dbsession = DBSession() country = dbsession.query(Country).filter_by(id=id).one() if country is None: request.session.flash("error;Country not found!") return HTTPFound(location=request.route_url("country_list")) form = Form(request, schema=CountryForm, obj=country) if "form_submitted" in request.POST and form.validate(): form.bind(country) dbsession.add(country) request.session.flash("warning;The Country is saved!") return HTTPFound(location = request.route_url("country_list")) action_url = request.route_url("country_edit", id=id) return dict(form=FormRenderer(form), action_url=action_url)
def test_bind_with_include(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" request.POST['name'] = 'test' form = Form(request, SimpleFESchema) form.validate() obj = form.bind(SimpleObj(), include=['foo']) self.assert_(obj.name == None)
def health_unit_type_save_view(request): form = Form(request, schema=HealthUnitTypeSchema()) if form.validate(): health_unit_type = form.bind(models.HealthUnitType()) with transaction.manager: models.DBSession.add(health_unit_type) return exc.HTTPFound(request.route_url("health_unit_type_list", \ page="Health Unit Types", headings= headings)) else: print "Validation Failed!!!!" print form.all_errors()
def test_bind(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" request.POST["name"] = "test" form = Form(request, SimpleFESchema) form.validate() obj = form.bind(SimpleObj()) self.assert_(obj.name == "test")
def wiki_update(request): title = request.matchdict["title"] # request.POST["title"] = title page = _get_page(title) if not page: page = WikiPage() page.title = title form = Form(request, method="PUT", schema=WikiPageSchema, obj=page) if form.validate(): form.bind(page, include=["body", "title"]) page.revision = (page.revision or 0) + 1 # sqlalchemy "default" doesn't work here? page.user = request.user page.user_ip = request.user.ip DBSession.add(page) return HTTPFound(request.route_url("wiki", title=page.title)) else: logger.warning("Form failed validation: %r %r" % (request.POST, form.errors)) index = _get_page(u"wiki:sidebar") return {"form": FormRenderer(form), "page": page, "index": index}
def concept_datatype_save_view(request): print "Reached ME!!!" if "concept_datatype" in request.POST: form = Form(request, schema=ConceptDataTypeSchema) if form.validate(): concept_datatype = form.bind(models.ConceptDataType()) with transaction.manager: models.DBSession.merge(concept_datatype) return HTTPFound( request.route_url("concept_datatype_list_page", page="Concept Data Type", headings=concept_headings, items=concept_datatypes()))
def new(request): """new country """ form = Form(request, schema=CountryForm) if "form_submitted" in request.POST and form.validate(): dbsession = DBSession() country = form.bind(Country()) # TODO: db error control? dbsession.add(country) request.session.flash("warning;New Country is saved!") return HTTPFound(location=request.route_url("country_list")) return dict(form=FormRenderer(form), action_url=request.route_url("country_new"))
def create_note(request): user = get_current_user(request) form = Form( request, schema=NoteSchema(), state=State(user=user)) if form.validate(): note = form.bind(Note()) note.user = user DBSession.add(note) request.session.flash(u'Note is successfully created', 'success') return HTTPFound(location=request.route_url('notes')) return _response_dict( request, renderer=FormRenderer(form) )
def add(request): import ipdb ipdb.set_trace() form = Form(request, schema=NoteSchema) if form.validate(): obj = form.bind(Note()) # persist model somewhere... return HTTPFound(location='/') return dict(renderer=FormRenderer(form))
def abt_update(self): user = self.request.user form = Form(self.request, schema=NoteSchema, obj=user) if "abt_submitted" in self.request.POST and form.validate(): form.bind(user) DBSession.add(user) DBSession.flush() if self.request.is_xhr: html = """<div class="alert alert-success alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update Successful </div>""" return Response(html) self.session.flash("success; Update successful") return HTTPFound(location=self.request.route_url("user_edit")) if self.request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update Not Successful </div>""" return Response(html) self.session.flash("danger; Update Not successful") return HTTPFound(location=self.request.route_url("user_edit"))
def email_passw(request): user = request.user form = Form(request, schema=ChangeEmailPassword, obj=user) if 'pass_submitted' in request.POST and form.validate(): form.bind(user) DBSession.add(user) DBSession.flush() if request.is_xhr: html = """<div class="alert alert-success alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update Successful </div>""" return Response(html) request.session.flash("success; Email and password saved") return HTTPFound(location=request.route_url('account')) if request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update not Successful {0} </div>""".format(form.all_errors()) return Response(html) request.session.flash("danger; Update not successful") return HTTPFound(location=request.route_url('account'))
def blog_category_edit(request): title = 'Edit blog category' id = request.matchdict['id'] parent_categories = DBSession.query(BlogCategory).filter( BlogCategory.parent == None).all() parent_categories = [(x.id, x.name) for x in parent_categories] category = BlogCategory.get_by_id(id) if category is None: request.session.flash("warning; Category not found!") return HTTPFound(location=request.route_url("blog_category_list")) form = Form(request, schema=BlogCategoryForm, obj=category) if "form_submitted" in request.POST and form.validate(): form.bind(category) DBSession.add(category) request.session.flash("success;The Category is saved!") return HTTPFound(location=request.route_url("blog_category_list")) action_url = request.route_url("blog_category_edit", id=id) return dict(form=FormRenderer(form), category=category, parent_categories=parent_categories, action_url=action_url)
def edit(request): """customer edit """ id = request.matchdict['id'] dbsession = DBSession() customer = dbsession.query(Customer).filter_by(id=id).one() if customer is None: request.session.flash("error;Customer not found!") return HTTPFound(location=request.route_url("customer_list")) categories = get_categories() countries = get_countries() form = Form(request, schema=CustomerForm, obj=customer) if "form_submitted" in request.POST and form.validate(): form.bind(customer) dbsession.add(customer) request.session.flash("warning;The Customer is saved!") return HTTPFound(location=request.route_url("customer_list")) action_url = request.route_url("customer_edit", id=id) return dict(form=FormRenderer(form), categories=categories, countries=countries, action_url=action_url)
def person_relation_save_view(request): health_id = request.matchdict["health_id"] print request.params.mixed() person_a = request.params['person_a'] person_b = request.params['person_b'] form = Form(request, RelationshipSchema()) if form.validate(): relationship = form.bind(models.Relationship()) with transaction.manager: models.DBSession.add(relationship) return HTTPFound( request.route_url("patient_dashboard_page", health_id=person_a)) else: print form.all_errors()
def restore_password_view(request): token = request.matchdict['token'] form = Form(request, schema=RestoreUserPasswordSchema) user = request.dbsession.query(User).filter(User.token == token).first() if user is None: request.session.flash( 'danger; Token error try again or connect to developer') return HTTPFound(request.route_path('home')) if form.validate(): item = User() form.bind(item) user.password = hash_password(item.password) user.token = None user.activated = True log.debug(user.password) request.dbsession.flush() request.session.flash('success; Password changed') return HTTPFound(request.route_path('home')) return { 'form': FormRenderer(form), }
def person_add_view(request): health_id = request.POST['health_id'] form = Form(request, schema=PersonSchema()) if form.validate(): person = form.bind(models.Person()) with transaction.manager: models.DBSession.add(person) return HTTPFound(request.route_url("patient_dashboard_page",\ health_id=health_id, page= "Patient Dashboard")) #page= "Patients List", health_id= health_id) else: print "Form Validation Failed" print form.all_errors() print request.POST return {"message": "Reched ME!!"}
def update_pad(request): pad_id = request.matchdict['pad_id'] pad = DBSession.query(Pad).filter( Pad.id == pad_id, Pad.user_id == get_current_user(request).id ).first() or raise_404(text='Pad not found') form = Form(request, schema=PadSchema(), obj=pad) if form.validate(): pad = form.bind(pad) pad.user = get_current_user(request) DBSession.add(pad) request.session.flash(u'Pad is successfully updated', 'success') return HTTPFound( location=request.route_url('pad_notes', pad_id=pad.id) ) return _response_dict(request, renderer=FormRenderer(form), pad=pad)
def register(self): form = Form(self.request, schema=UserSchema) if form.validate(): user = form.bind(resources.User()) user.password, user.salt = gen_hash_password(user.password) personal_tag = resources.Tag() personal_tag.label = user.email personal_tag.tag_type = 'user' personal_tag.tag_permission = 2 personal_tag.save() user.personal_tag = personal_tag user.save() user = authenticate_user(self.request.params['email'], self.request.params['password']) headers = remember(self.request, str(user.id)) return HTTPFound(location="/", headers=headers) return {'renderer': FormRenderer(form)}
def new(request): """new customer """ categories = get_categories() countries = get_countries() form = Form(request, schema=CustomerForm) if "form_submitted" in request.POST and form.validate(): dbsession = DBSession() customer = form.bind(Customer()) dbsession.add(customer) request.session.flash("warning;New Customer is saved!") return HTTPFound(location=request.route_url("customer_list")) return dict(form=FormRenderer(form), categories=categories, countries=countries, action_url=request.route_url("customer_new"))
def location_add(request): form = Form(request, schema=LocationSchema()) if form.validate(): location = form.bind(models.Location()) with transaction.manager: models.DBSession.add(location) locations = models.DBSession.query(models.Location).all() locations_list = [(location.id, location.name) for location in locations] return { "page": "Locations", "items": locations_list, "headings": headings } else: print form.all_errors() print form.errors_for('parent') print "Form validation failed"
def test_bind_ignore_underscores(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" request.POST['name'] = 'test' request.POST['_ignoreme'] = 'test' class SimpleObjWithPrivate(SimpleObj): _ignoreme = None class SimpleFESchemaWithPrivate(SimpleFESchema): _ignoreme = validators.String() form = Form(request, SimpleFESchemaWithPrivate) form.validate() obj = form.bind(SimpleObjWithPrivate()) self.assert_(obj.name == 'test') self.assert_(obj._ignoreme is None)
def user_add_view(request): """ Render the add user form page. Display an empty user form or validate the user submited form. If the form is validated then add the user datas to the database and a success flash message. If the form is not valid, then display again the form with validation errors. Return also a list of groups to use in the group select form. :param request: a ``pyramid.request`` object """ _ = request.translate grouplist = get_grouplist() form = Form(request, schema=UserForm) if 'form_submitted' in request.params and form.validate(): user = form.bind(AuthUser()) DBSession.add(user) request.session.flash(_(u"User added."), 'success') return HTTPFound(location=request.route_path('tools.user_list')) return dict(renderer=FormRenderer(form), grouplist=grouplist)
def visit_save_view(request): health_id = request.matchdict['health_id'] form_id = request.matchdict["form"] visit_date = request.POST["visit_date"] health_unit = request.POST["health_unit"] observations = [] person = None with transaction.manager: person = models.DBSession.query(models.Person).\ filter(models.Person.health_id == health_id).first() form = Form(request, schema=VisitSchema()) if form.validate(): for param,value in request.POST.iteritems(): try: param =int(param) print param, value,'\n' with transaction.manager: concept = models.DBSession.query(models.Concept).get(param) if concept: observation = models.Observation() observation.concept = param observation.concept_value observations.append(observation) except ValueError: continue visit = form.bind(models.Visit()) visit.person = person.id visit.observations = observations models.DBSession.add(visit) models.DBSession.flush() #with transaction.manager: # visit.observations = observations # models.DBSession.merge(visit) else: #print form.all_errors() print form.is_error(visit_date) print request.POST return HTTPFound(request.route_url("patients_list_page"))
def update_note(request): user = get_current_user(request) note_id = request.matchdict['note_id'] note = DBSession.query(Note).filter(Note.id == note_id).first() form = Form( request, schema=NoteSchema(), state=State(user=user), obj=note) if form.validate(): note = form.bind(note) DBSession.add(note) request.session.flash(u'Note is successfully updated', 'success') # build redirect url location = request.route_url('notes') if note.pad is not None: location = request.route_url('pad_notes', pad_id=note.pad.id) return HTTPFound(location=location) return _response_dict( request, note=note, renderer=FormRenderer(form) )
def health_unit_add(request): form = Form(request, schema=HealthUnitSchema()) health_unit_id = None if form.validate(): health_unit = form.bind(models.HealthUnit()) h_unit = None #with transaction.manager: #location = models.DBSession.query(models.Location).get(health_unit.location) #unit_type = models.DBSession.query(models.HealthUnitType).get(health_unit.health_unit_type_id) #health_unit.location = location #health_unit.health_unit_type_id = unit_type h_unit = models.DBSession.merge(health_unit) models.DBSession.flush() models.DBSession.close() health_unit_id = h_unit.id print "HEALTH UNIT ID: ", health_unit_id health_units = models.DBSession.query(models.HealthUnit).all() units = [(health_unit.id, health_unit.name) for health_unit in health_units] return exc.HTTPFound(request.route_url("health_unit_dashboard", health_unit_id=health_unit_id,page="Health Units", items=units, headings=health_unit_headings)) else: print form.all_errors() return "Failed"
class ModelState(object): def __init__(self, request): self.form = Form(request) self.renderer = CiocFormRenderer(self.form) self._defaults = None @property def is_valid(self): return not self.form.errors @property def schema(self): return self.form.schema @schema.setter def schema(self, value): if self.form.schema: raise RuntimeError, \ "schema property has already been set" self.form.schema = value @property def validators(self): return self.form.validators @validators.setter def validators(self, value): if self.form.validators: raise RuntimeError, \ "validators property has alread been set" self.form.validators = value @property def method(self): return self.form.method @method.setter def method(self, value): self.form.method = value @property def defaults(self): return self._defaults @defaults.setter def defaults(self, value): if self._defaults: raise RuntimeError, \ "defaults property has already been set" if self.form.is_validated: raise RuntimeError, \ "Form has already been validated" self._defaults = value self.form.data.update(value) @property def data(self): return self.form.data def validate(self, *args, **kw): return self.form.validate(*args, **kw) def bind(self, obj=None, include=None, exclude=None): if obj is None: obj = DefaultModel() return self.form.bind(obj, include, exclude) def value(self, name, default=None): return self.renderer.value(name, default) def is_error(self, name): return self.renderer.is_error(name) def errors(self): return self.form.errors def errors_for(self, name): return self.renderer.errors_for(name) def add_error_for(self, name, msg): errlist = self.form.errors_for(name) errlist.append(msg) self.form.errors[name] = errlist
class ModelState: def __init__(self, request): def formencode_translator(x): if not isinstance(x, TranslationString): x = fe_tsf(x) return gettext(x, request) self.form = Form(request, state=State(_=formencode_translator, request=request)) self.renderer = CiocFormRenderer(self.form) self._defaults = None @property def is_valid(self): if not self.form.is_validated: raise RuntimeError( "Form has not been validated. Call validate() first") return not self.form.validate() @property def schema(self): return self.form.schema @schema.setter # NOQA def schema(self, value): if self.form.schema: raise RuntimeError("schema property has already been set") self.form.schema = value @property def validators(self): return self.form.validators @validators.setter # NOQA def validators(self, value): if self.form.validators: raise RuntimeError("validators property has alread been set") self.form.validators = value @property def method(self): return self.form.method @method.setter # NOQA def method(self, value): self.form.method = value @property def defaults(self): return self._defaults @defaults.setter # NOQA def defaults(self, value): if self._defaults: raise RuntimeError("defaults property has already been set") if self.form.is_validated: raise RuntimeError("Form has already been validated") self._defaults = value self.form.data.update(value) def validate(self, *args, **kw): return self.form.validate(*args, **kw) def bind(self, obj=None, include=None, exclude=None): if obj is None: obj = DefaultModel() return self.form.bind(obj, include, exclude) def value(self, name, default=None): return self.renderer.value(name, default) def is_error(self, name): return self.renderer.is_error(name) def errors_for(self, name): return self.renderer.errors_for(name)