| Trees | Indices | Help |
|
|---|
|
|
1
2
3 #def make_form(spec, request):
4 # form = {}
5 # for path, info in spec["fields"]:
6 # if info["type"] in ["text", "password"]:
7 # form[path] = {
8 # "value": request.POST.get(path, info.get("default", "")),
9 # "error": [],
10 # }
11 # return form
12
13
24
25
28 self.spec = spec
29 self.fields = {}
30 self.ordered_fields = []
31 self.errors = []
32
33 for path, info in spec["fields"]:
34 if info["type"] in ["str", "text", "password", "submit"]:
35 field = FieldValidation(info)
36 setattr(self, path, field)
37 self.fields[path] = field
38 self.ordered_fields.append([path, field])
39
40 if request != None:
41 self.load(request)
42
47
53
56
58 form = { "fields": [] }
59 for path, info in self.spec["fields"]:
60 field = dict(info)
61 if info["type"] in ["str", "text", "password"]:
62 field["value"] = self.fields[path].value
63 field["error"] = self.fields[path].errors
64 form["fields"].append([path, field])
65 form["description"] = self.spec.get("description", "")
66 form["action"] = self.spec.get("action", "")
67
68 return form
69
70
72 if fields == None:
73 fields = map(lambda x: x[0], schema["fields"])
74 for path in fields:
75 if not path in form.fields:
76 continue
77 field = form.fields[path]
78 info = dict(schema["fields"])[path]
79 if "required" in info and info["required"]:
80 if field.value == "":
81 field.error("%s is required." % info["label"])
82 continue
83
84 if info["type"] in ["str", "text", "password"]:
85 if "length" in info:
86 length = info["length"]
87 if "min" in length:
88 if len(field.value) < length["min"]:
89 field.error("%(label)s must be at least %(min)s characters long." %
90 { "label": info["label"], "min": length["min"]})
91 if "max" in length:
92 if len(field.value) > length["max"]:
93 field.error("%(label)s must be no longer than %(max)s characters." %
94 { "label": info["label"], "max": length["max"]})
95
96 if "pattern" in info:
97 import re
98 pattern, message = info["pattern"][:2]
99 regex = re.compile(pattern)
100 if not regex.match(field.value):
101 field.error(message % { "label": info["label"] })
102
103 if "equal_to" in info:
104 target, message = info["equal_to"][:2]
105 if field.value != form.fields[target].value:
106 field.error(message % { "label": info["label"],
107 "value": field.value,})
108
109 if info["type"] in ["submit"]:
110 pass
111
112 if len(field.errors) > 0:
113 continue
114
115 if "proc" in info:
116 function, message = info["proc"][:2]
117 if not function(field.value):
118 field.error(message % { "label": info["label"],
119 "value": field.value })
120
121 is_valid = True
122 for path in fields:
123 field = form.fields[path]
124 if len(field.errors) > 0:
125 is_valid = False
126
127 if not is_valid:
128 form.error("There were problems with your submission. Please correct the fields below.")
129
130 return form
131
| Trees | Indices | Help |
|
|---|
| Generated by Epydoc 3.0beta1 on Tue Jul 1 22:04:00 2008 | http://epydoc.sourceforge.net |