本文整理汇总了Python中pyramid_simpleform.Form.all_errors方法的典型用法代码示例。如果您正苦于以下问题:Python Form.all_errors方法的具体用法?Python Form.all_errors怎么用?Python Form.all_errors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid_simpleform.Form
的用法示例。
在下文中一共展示了Form.all_errors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: concept_save_view
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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"
示例2: health_unit_type_save_view
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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()
示例3: addpurchaselineitem
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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)
示例4: location_add
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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"
示例5: person_relation_save_view
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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()
示例6: person_add_view
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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!!"}
示例7: form_save
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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!!!"
示例8: test_all_errors_with_list
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
def test_all_errors_with_list(self):
from pyramid_simpleform import Form
request = testing.DummyRequest()
request.method = "POST"
form = Form(request, SimpleFESchema)
form.errors = [u"Name is missing"]
self.assert_(form.all_errors() == [u"Name is missing"])
示例9: test_all_errors_with_dict
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
def test_all_errors_with_dict(self):
from pyramid_simpleform import Form
request = testing.DummyRequest()
request.method = "POST"
form = Form(request, SimpleFESchema)
form.errors = {"name": [u"Name is missing"], "value": u"Value is missing"}
self.assert_(sorted(form.all_errors()) == sorted([u"Name is missing", u"Value is missing"]))
示例10: health_unit_add
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
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"
示例11: test_error_with_jsonbody
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
def test_error_with_jsonbody(self):
from pyramid_simpleform import Form
request = testing.DummyRequest()
request.method = "POST"
import json
request.json_body = json.loads("{}")
form = Form(request, SimpleFESchema)
form.errors = {"name": [u"Name is missing"], "value": u"Value is missing"}
self.assert_(sorted(form.all_errors()) == sorted([u"Name is missing", u"Value is missing"]))
示例12: login_view
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
def login_view(request):
"""
Perform a 'login' by getting the service document from a sword repository.
"""
templatePath = "templates/login.pt"
config = load_config(request)
form = Form(request, schema=LoginSchema)
field_list = [("username",), ("password",)]
session = request.session
# validate the form in order to compute all errors
valid_form = form.validate()
request["errors"] = form.all_errors()
# Check for successful form completion
if "form.submitted" in request.POST and valid_form:
if form.data["anonymous"]:
login = AnonymousSession()
else:
login = auth(form.data["service_document_url"], form.data["username"], form.data["password"])
if login is None:
request["errors"] = ["Invalid username or password. Please try again."]
response = {"form": FormRenderer(form), "field_list": field_list, "config": config}
return render_to_response(templatePath, response, request=request)
# The login details are persisted on the session.
if TESTING:
session["login"] = TestingSession()
else:
session["login"] = login
return HTTPFound(location=request.route_url("choose"))
elif "login" in session:
return HTTPFound(location=request.route_url("choose"))
# If not signed in, go to login page
response = {"form": FormRenderer(form), "field_list": field_list, "config": config}
return render_to_response(templatePath, response, request=request)
示例13: navigate
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
def navigate(self, errors=None, form=None):
request = self.request
neworexisting_form = Form(request, schema=NewOrExistingSchema)
officedocument_form = Form(request, schema=OfficeDocumentUploadSchema)
googledocs_form = Form(request, schema=GoogleDocsSchema)
url_form = Form(request, schema=URLSchema)
presentationform = Form(request, schema=PresentationSchema)
zip_or_latex_form = Form(request, schema=ZipOrLatexSchema)
LOG.info(presentationform.all_errors())
#TODO: This can be replaced by utility/adapter lookups
# Check for successful form completion
if neworexisting_form.validate():
return self._process_neworexisting_submit(request, neworexisting_form)
elif officedocument_form.validate():
return self._process_officedocument_submit(request, officedocument_form)
elif googledocs_form.validate():
return self._process_googledocs_submit(request, googledocs_form)
elif url_form.validate():
return self._process_url_submit(request, url_form)
elif presentationform.validate():
return self._process_presentationform_submit(request, presentationform)
elif zip_or_latex_form.validate():
return self._process_zip_or_latex_form(request, zip_or_latex_form)
templatePath = 'templates/choose.pt'
# First view or errors
response = {
'neworexisting_form': FormRenderer(neworexisting_form),
'officedocument_form': FormRenderer(officedocument_form),
'googledocs_form': FormRenderer(googledocs_form),
'url_form': FormRenderer(url_form),
'presentationform': FormRenderer(presentationform),
'zip_or_latex_form': FormRenderer(zip_or_latex_form),
'view': self,
}
return render_to_response(templatePath, response, request=self.request)
示例14: enhance
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
def enhance(request):
check_login(request)
session = request.session
google_resource_id = ""
slideshare_id = ""
embed_google = False
embed_slideshare = False
not_converted = True
show_iframe = False
form = Form(request, schema=QuestionAnswerSchema)
validate_form = form.validate()
print form.all_errors()
if session.has_key('google-resource-id'):
google_resource_id = session['google-resource-id']
if session.has_key('slideshare_id'):
slideshare_id = session['slideshare_id']
if fetch_slideshow_status(slideshare_id) == "2":
not_converted = False
show_iframe = True
if google_resource_id!="":
embed_google = True
if slideshare_id!="":
embed_slideshare = True
templatePath = "templates/google_ss_preview.pt"
if validate_form:
introductory_paragraphs = request.POST.get('introductory_paragraphs')
question_count=0
cnxml=session["cnxml"]+"""<content><section id="intro-section-title"><title id="introtitle">Introduction</title><para id="introduction-1">"""+introductory_paragraphs+"""</para></section><section id="slides-embed"><title id="slide-embed-title">View the slides</title><figure id="ss-embed-figure"><media id="slideshare-embed" alt="slideshare-embed"><iframe src="http://www.slideshare.net/slideshow/embed_code/"""+slideshare_id+"""" width="425" height="355" /></media></figure></section>"""
for i in range(1,6):
form_question = request.POST.get('question-'+str(i))
if form_question:
form_radio_answer = request.POST.get('radio-'+str(i)) #this give us something like 'answer-1-1'. so our solution is this
question_count +=1
if question_count==1:
cnxml+="""<section id="test-section"><title>Test your knowledge</title>"""
itemlist = ""
for j in range(1,10):
try:
form_all_answers = request.POST.get('answer-'+str(i)+'-'+str(j))
if form_all_answers:
itemlist +="<item>" + form_all_answers+"</item>"
except:
print "No element found"
if form_radio_answer:
solution = request.POST.get(form_radio_answer)
cnxml+="""<exercise id="exercise-"""+str(i)+""""><problem id="problem-"""+str(i)+""""><para id="para-"""+str(i)+"""">"""+str(form_question)+"""<list id="option-list-"""+str(i)+"""" list-type="enumerated" number-style="lower-alpha">"""+str(itemlist)+"""</list></para></problem>"""
else:
print "ELESE CONDUITION OF radio"
solution = request.POST.get('answer-'+str(i)+'-1')
cnxml+="""<exercise id="exercise-"""+str(i)+""""><problem id="problem-"""+str(i)+""""><para id="para-"""+str(i)+"""">"""+str(form_question)+"""</para></problem>"""
print "FORM RADIO ANSWER",form_radio_answer
print "SOLUTION", solution
cnxml+=""" <solution id="solution-"""+str(i)+""""> <para id="solution-para-"""+str(i)+"""">"""+solution+"""</para></solution></exercise>"""
"""form_solution = request.POST.get('solution-'+str(i))
all_post_data = {"data":{"options":form_options,"solution":form_solution,"question":form_question}}
for question in all_post_data:
options = all_post_data[question]['options']
solution = all_post_data[question]['solution']
asked_question = all_post_data[question]['question']
optionlist=""
for option in options:
optionlist+="<item>"+option+"</item>"""
#cnxml+="""<exercise id="exercise-"""+str(j)+""""><problem id="problem-"""+str(j)+""""><para id="para-"""+str(j)+"""">"""+str(asked_question)+"""<list id="option-list-"""+str(j)+"""" list-type="enumerated" number-style="lower-alpha">"""+str(optionlist)+"""</list></para></problem>"""
#cnxml+=""" <solution id="solution-"""+str(j)+""""> <para id="solution-para-"""+str(j)+"""">"""+solution+"""</para></solution></exercise>"""
#j+=1
metadata = session['metadata']
if question_count>=1:
cnxml += "</section></content></document>"
else:
cnxml += "</content></document>"
workspaces = [(i['href'], i['title']) for i in session['login'].collections]
metadata_entry = sword2cnx.MetaData(metadata)
zipped_filepath = session['userfilepath']
zip_archive = zipfile.ZipFile(zipped_filepath, 'w')
zip_archive.writestr("index.cnxml",cnxml)
zip_archive.close()
conn = sword2cnx.Connection("http://cnx.org/sword/servicedocument",
user_name=session['login'].username,
user_pass=session['login'].password,
always_authenticate=True,
download_service_document=True)
collections = [{'title': i.title, 'href': i.href}
for i in sword2cnx.get_workspaces(conn)]
session['login'].collections = collections
workspaces = [(i['href'], i['title']) for i in session['login'].collections]
session['workspaces'] = workspaces
with open(zipped_filepath, 'rb') as zip_file:
deposit_receipt = conn.create(
col_iri = workspaces[0][0],
metadata_entry = metadata_entry,
payload = zip_file,
filename = 'upload.zip',
#.........这里部分代码省略.........
示例15: login_view
# 需要导入模块: from pyramid_simpleform import Form [as 别名]
# 或者: from pyramid_simpleform.Form import all_errors [as 别名]
def login_view(request):
"""
Perform a 'login' by getting the service document from a sword repository.
"""
templatePath = 'templates/login.pt'
config = load_config(request)
form = Form(request, schema=LoginSchema)
field_list = [
('username',),
('password',),
]
session = request.session
# validate the form in order to compute all errors
valid_form = form.validate()
request['errors'] = form.all_errors()
# Check for successful form completion
if 'form.submitted' in request.POST and valid_form:
# The login details are persisted on the session
for field_name in [i[0] for i in field_list]:
session[field_name] = form.data[field_name]
session['service_document_url'] = form.data['service_document_url']
loggedIn = True
# Check if user is already authenticated
else:
loggedIn = True
for key in ['username', 'password', 'service_document_url', 'collections', 'workspace_title', 'sword_version', 'maxuploadsize']:
if not session.has_key(key):
loggedIn = False
if loggedIn:
return HTTPFound(location=request.route_url('choose'))
# TODO: check credentials against Connexions and ask for login
# again if failed.
# If not signed in, go to login page
if not loggedIn:
response = {
'form': FormRenderer(form),
'field_list': field_list,
'config': config,
}
return render_to_response(templatePath, response, request=request)
# Here we know that the user is authenticated and that they did so
# by logging in (rather than having had a cookie set already)
if TESTING:
session['workspace_title'] = "Connexions"
session['sword_version'] = "2.0"
session['maxuploadsize'] = "60000"
session['collections'] = [{'title': 'Personal Workspace', 'href': 'http://'}]
else:
# Get the service document and persist what's needed.
conn = sword2cnx.Connection(session['service_document_url'],
user_name=session['username'],
user_pass=session['password'],
always_authenticate=True,
download_service_document=True)
try:
# Get available collections from SWORD service document
# We create a list of dictionaries, otherwise we'll have problems
# pickling them.
if not conn.sd.valid:
raise Exception
session['collections'] = [{'title': i.title, 'href': i.href}
for i in sword2cnx.get_workspaces(conn)]
except:
del session['username']
del session['password']
request['errors'] = ["Invalid username or password. Please try again.",]
response = {
'form': FormRenderer(form),
'field_list': field_list,
'config': config,
}
return render_to_response(templatePath, response, request=request)
# Get needed info from the service document
doc = etree.fromstring(conn.sd.raw_response)
# Prep the namespaces. xpath does not like a None namespace.
namespaces = doc.nsmap
del namespaces[None]
# We need some details from the service document.
# TODO: This is fragile, since it assumes a certain structure.
session['workspace_title'] = doc.xpath('//atom:title',
namespaces=namespaces
)[0].text
session['sword_version'] = doc.xpath('//sword:version',
namespaces=namespaces
)[0].text
session['maxuploadsize'] = doc.xpath('//sword:maxuploadsize',
namespaces=namespaces
)[0].text
#.........这里部分代码省略.........