| 1 |
""" |
| 2 |
Widgets are small components that render form fields for inputing data in a |
| 3 |
certain format. |
| 4 |
|
| 5 |
Caution: the args argument in the widgets' render methods is a disaster |
| 6 |
in python3 -- it maps from bytes when there are errors (it's a t.w |
| 7 |
Request.args), from string otherwise (it's a formal-internal thing). |
| 8 |
And don't get me started on its values. |
| 9 |
""" |
| 10 |
|
| 11 |
# TODO: Fix this -- have a common sort of args for both cases in |
| 12 |
# some way. |
| 13 |
|
| 14 |
import itertools |
| 15 |
|
| •16 |
from gavo.pkg_resources import resource_filename |
| 17 |
from zope.interface import implementer |
| 18 |
from twisted.web import template |
| 19 |
from twisted.web.template import tags as T |
| 20 |
|
| 21 |
from . import iformal, validation, nevowc |
| 22 |
from .util import render_cssid |
| 23 |
|
| 24 |
|
| 25 |
# Marker object for args that are not supplied |
| 26 |
_UNSET = object() |
| 27 |
|
| 28 |
|
| 29 |
def getStringFromArgs(args, key, default=''): |
| 30 |
"""returns args[key][0] suitably decoded. |
| 31 |
|
| 32 |
This is used to insert erroneous inputs into fields from request.args. |
| 33 |
|
| 34 |
Default must already be a string, not bytes. |
| 35 |
|
| 36 |
Unfortunately, depending on the context, formal will pass in args |
| 37 |
with either string keys or bytes keys. While we can't rebuild |
| 38 |
the thing to be halfway sane, we simply adapt key based on some |
| 39 |
key we pick from args. Yeah, madness. |
| 40 |
""" |
| 41 |
if not args: |
| 42 |
return default |
| 43 |
if isinstance(next(iter(args)), str): |
| 44 |
if isinstance(key, bytes): |
| 45 |
key = key.decode("ascii") |
| 46 |
else: |
| 47 |
if isinstance(key, str): |
| 48 |
key = key.encode("ascii") |
| 49 |
|
| 50 |
if key in args and args[key]: |
| 51 |
return args[key][0].decode("utf-8", "replace") |
| 52 |
else: |
| 53 |
return default |
| 54 |
|
| 55 |
|
| 56 |
def perhapsDecode(val): |
| 57 |
"""returns val utf-8-decoded if it's bytes, unchanged otherwise. |
| 58 |
""" |
| 59 |
if isinstance(val, bytes): |
| 60 |
return val.decode("utf-8") |
| 61 |
return val |
| 62 |
|
| 63 |
|
| 64 |
@implementer( iformal.IWidget ) |
| 65 |
class TextInput(object): |
| 66 |
""" |
| 67 |
A text input field. |
| 68 |
|
| 69 |
<input type="text" ... /> |
| 70 |
""" |
| 71 |
|
| 72 |
inputType = 'text' |
| 73 |
showValueOnFailure = True |
| 74 |
placeholder = None |
| 75 |
|
| 76 |
def __init__(self, original): |
| 77 |
self.original = original |
| 78 |
|
| 79 |
def _renderTag(self, request, key, value, readonly): |
| 80 |
tag=T.input(type=self.inputType, name=key, id=render_cssid(key)) |
| 81 |
if value is not None: |
| 82 |
tag(value=str(value)) |
| 83 |
if readonly: |
| 84 |
tag(class_='readonly', readonly='readonly') |
| 85 |
if self.placeholder is not None: |
| 86 |
tag(placeholder=self.placeholder) |
| 87 |
return tag |
| 88 |
|
| 89 |
def render(self, request, key, args, errors): |
| 90 |
if errors: |
| 91 |
value = getStringFromArgs(args, key) |
| 92 |
else: |
| 93 |
value = iformal.IStringConvertible(self.original).fromType( |
| 94 |
args.get(key)) |
| 95 |
if not self.showValueOnFailure: |
| 96 |
value = None |
| 97 |
return self._renderTag(request, key, value, False) |
| 98 |
|
| 99 |
def renderImmutable(self, request, key, args, errors): |
| 100 |
value = iformal.IStringConvertible(self.original).fromType( |
| 101 |
args.get(key)) |
| 102 |
return self._renderTag(request, key, value, True) |
| 103 |
|
| 104 |
def processInput(self, request, key, args, default=''): |
| 105 |
value = getStringFromArgs(args, key, default) |
| 106 |
value = iformal.IStringConvertible(self.original).toType(value) |
| 107 |
return self.original.validate(value) |
| 108 |
|
| 109 |
|
| 110 |
@implementer( iformal.IWidget ) |
| 111 |
class Checkbox(object): |
| 112 |
""" |
| 113 |
A checkbox input field. |
| 114 |
|
| 115 |
<input type="checkbox" ... /> |
| 116 |
""" |
| 117 |
|
| 118 |
def __init__(self, original): |
| 119 |
self.original = original |
| 120 |
|
| 121 |
def _renderTag(self, request, key, value, disabled): |
| 122 |
tag = T.input(type='checkbox', name=key, id=render_cssid(key), value='True') |
| 123 |
if value == 'True': |
| 124 |
tag(checked='checked') |
| 125 |
if disabled: |
| 126 |
tag(class_='disabled', disabled='disabled') |
| 127 |
return tag |
| 128 |
|
| 129 |
def render(self, request, key, args, errors): |
| 130 |
if errors: |
| 131 |
value = getStringFromArgs(args, key) |
| 132 |
else: |
| 133 |
value = iformal.IBooleanConvertible(self.original).fromType( |
| 134 |
args.get(key)) |
| 135 |
return self._renderTag(request, key, value, False) |
| 136 |
|
| 137 |
def renderImmutable(self, request, key, args, errors): |
| 138 |
value = iformal.IBooleanConvertible(self.original).fromType( |
| 139 |
args.get(key)) |
| 140 |
return self._renderTag(request, key, value, True) |
| 141 |
|
| 142 |
def processInput(self, request, key, args, default=''): |
| 143 |
value = getStringFromArgs(args, key, default) |
| 144 |
if not value: |
| 145 |
value = 'False' |
| 146 |
value = iformal.IBooleanConvertible(self.original).toType(value) |
| 147 |
return self.original.validate(value) |
| 148 |
|
| 149 |
|
| 150 |
class Password(TextInput): |
| 151 |
""" |
| 152 |
A text input field that hides the text. |
| 153 |
|
| 154 |
<input type="password" ... /> |
| 155 |
""" |
| 156 |
inputType = 'password' |
| 157 |
showValueOnFailure = False |
| 158 |
|
| 159 |
|
| 160 |
@implementer( iformal.IWidget ) |
| 161 |
class TextArea(object): |
| 162 |
""" |
| 163 |
A large text entry area that accepts newline characters. |
| 164 |
|
| 165 |
<textarea>...</textarea> |
| 166 |
""" |
| 167 |
|
| 168 |
cols = 48 |
| 169 |
rows = 6 |
| 170 |
|
| 171 |
def __init__(self, original, cols=None, rows=None): |
| 172 |
self.original = original |
| 173 |
if cols is not None: |
| 174 |
self.cols = cols |
| 175 |
if rows is not None: |
| 176 |
self.rows = rows |
| 177 |
|
| 178 |
def _renderTag(self, request, key, value, readonly): |
| 179 |
tag=T.textarea(name=key, |
| 180 |
id=render_cssid(key), |
| 181 |
cols=str(self.cols), |
| 182 |
rows=str(self.rows))[str(value or '')] |
| 183 |
if readonly: |
| 184 |
tag(class_='readonly', readonly='readonly') |
| 185 |
return tag |
| 186 |
|
| 187 |
def render(self, request, key, args, errors): |
| 188 |
if errors: |
| 189 |
value = getStringFromArgs(args, key) |
| 190 |
else: |
| 191 |
value = iformal.IStringConvertible(self.original).fromType( |
| 192 |
args.get(key)) |
| 193 |
return self._renderTag(request, key, value or "", False) |
| 194 |
|
| 195 |
def renderImmutable(self, request, key, args, errors): |
| 196 |
value = iformal.IStringConvertible(self.original).fromType( |
| 197 |
args.get(key)) |
| 198 |
return self._renderTag(request, key, value, True) |
| 199 |
|
| 200 |
def processInput(self, request, key, args, default=''): |
| 201 |
value = getStringFromArgs(args, key, default) |
| 202 |
value = iformal.IStringConvertible(self.original).fromType(value) |
| 203 |
return self.original.validate(value) |
| 204 |
|
| 205 |
|
| 206 |
@implementer( iformal.IWidget ) |
| 207 |
class TextAreaList(object): |
| 208 |
""" |
| 209 |
A text area that allows a list of values to be entered, one per line. Any |
| 210 |
empty lines are discarded. |
| 211 |
""" |
| 212 |
|
| 213 |
cols = 48 |
| 214 |
rows = 6 |
| 215 |
|
| 216 |
def __init__(self, original, cols=None, rows=None): |
| 217 |
self.original = original |
| 218 |
if cols is not None: |
| 219 |
self.cols = cols |
| 220 |
if rows is not None: |
| 221 |
self.rows = rows |
| 222 |
|
| 223 |
def _renderTag(self, request, key, values, readonly): |
| 224 |
value = '\n'.join(values) |
| 225 |
tag=T.textarea(name=key, |
| 226 |
id=render_cssid(key), |
| 227 |
cols=str(self.cols), |
| 228 |
rows=str(self.rows))[str(value or '')] |
| 229 |
if readonly: |
| 230 |
tag(class_='readonly', readonly='readonly') |
| 231 |
return tag |
| 232 |
|
| 233 |
def render(self, request, key, args, errors): |
| 234 |
converter = iformal.IStringConvertible(self.original.type) |
| 235 |
if errors: |
| 236 |
values = args.get(key, []) |
| 237 |
else: |
| 238 |
values = args.get(key) |
| 239 |
if values is not None: |
| 240 |
values = [converter.fromType(v) for v in values] |
| 241 |
else: |
| 242 |
values = [] |
| 243 |
return self._renderTag(request, key, values, False) |
| 244 |
|
| 245 |
def renderImmutable(self, request, key, args, errors): |
| 246 |
converter = iformal.IStringConvertible(self.original.type) |
| 247 |
values = args.get(key) |
| 248 |
if values is not None: |
| 249 |
values = [converter.fromType(v) for v in values] |
| 250 |
else: |
| 251 |
values = [] |
| 252 |
return self._renderTag(request, key, values, True) |
| 253 |
|
| 254 |
def processInput(self, request, key, args, default=''): |
| 255 |
# Get the whole string |
| 256 |
value = getStringFromArgs(args, key, default) |
| 257 |
# Split into lines |
| 258 |
values = value.splitlines() |
| 259 |
# Strip each line |
| 260 |
values = [v.strip() for v in values] |
| 261 |
# Discard empty lines |
| 262 |
values = [v for v in values if v] |
| 263 |
# Convert values to correct type |
| 264 |
converter = iformal.IStringConvertible(self.original.type) |
| 265 |
values = [converter.toType(v) for v in values] |
| 266 |
# Validate and return |
| 267 |
return self.original.validate(values) |
| 268 |
|
| 269 |
|
| 270 |
@implementer( iformal.IWidget ) |
| 271 |
class CheckedPassword(object): |
| 272 |
""" |
| 273 |
Two password entry fields that must contain the same value to validate. |
| 274 |
""" |
| 275 |
|
| 276 |
def __init__(self, original): |
| 277 |
self.original = original |
| 278 |
|
| 279 |
def render(self, request, key, args, errors): |
| 280 |
if errors and not errors.getFieldError(key): |
| 281 |
values = args.get(key) |
| 282 |
else: |
| 283 |
values = ('', '') |
| 284 |
return [ |
| 285 |
T.input(type='password', name=key, id=render_cssid(key), |
| 286 |
value=str(values[0])), |
| 287 |
T.br, |
| 288 |
T.label(for_=render_cssid(key, 'confirm'))[' Confirm '], |
| 289 |
T.input(type='password', name=key, id=render_cssid(key, 'confirm'), value=str(values[1])), |
| 290 |
] |
| 291 |
|
| 292 |
def renderImmutable(self, request, key, args, errors): |
| 293 |
values = ('', '') |
| 294 |
return [ |
| 295 |
T.input(type='password', name=key, id=render_cssid(key), |
| 296 |
value=str(values[0]), class_='readonly', readonly='readonly'), |
| 297 |
T.br, |
| 298 |
T.label(for_=render_cssid(key, 'confirm'))[' Confirm '], |
| 299 |
T.input(type='password', name=key, id=render_cssid(key, 'confirm'), |
| 300 |
value=str(values[1]), class_='readonly', |
| 301 |
readonly='readonly') |
| 302 |
] |
| 303 |
|
| 304 |
def processInput(self, request, key, args, default=''): |
| 305 |
pwds = [perhapsDecode(pwd) for pwd in args.get(key, [])] |
| 306 |
if len(pwds) == 0: |
| 307 |
pwds = ["", ""] |
| 308 |
elif len(pwds) == 1: |
| 309 |
raise validation.FieldValidationError('Please enter the password twice for confirmation.') |
| 310 |
else: |
| 311 |
if pwds[0] != pwds[1]: |
| 312 |
raise validation.FieldValidationError('Passwords do not match.') |
| 313 |
return self.original.validate(pwds[0]) |
| 314 |
|
| 315 |
|
| 316 |
class ChoiceBase(object): |
| 317 |
""" |
| 318 |
A base class for widgets that provide the UI to select one or more items |
| 319 |
from a list. |
| 320 |
|
| 321 |
options: |
| 322 |
A sequence of objects adaptable to IKey and ILabel. IKey is used as the |
| 323 |
<option>'s value attribute; ILabel is used as the <option>'s child. |
| 324 |
IKey and ILabel adapters for tuple are provided. |
| 325 |
noneOption: |
| 326 |
An object adaptable to IKey and ILabel that is used to identify when |
| 327 |
nothing has been selected. |
| 328 |
""" |
| 329 |
|
| 330 |
options = None |
| 331 |
noneOption = None |
| 332 |
|
| 333 |
def __init__(self, original, options=None, noneOption=_UNSET): |
| 334 |
self.original = original |
| 335 |
if options is not None: |
| 336 |
self.options = options |
| 337 |
if noneOption is not _UNSET: |
| 338 |
self.noneOption = noneOption |
| 339 |
|
| 340 |
def processInput(self, request, key, args, default=''): |
| 341 |
value = getStringFromArgs(args, key, default) |
| 342 |
value = iformal.IStringConvertible(self.original).toType(value) |
| 343 |
if self.noneOption is not None and \ |
| 344 |
value == iformal.IKey(self.noneOption).key(): |
| 345 |
value = None |
| 346 |
return self.original.validate(value) |
| 347 |
|
| 348 |
|
| 349 |
@implementer( iformal.IWidget ) |
| 350 |
class SelectChoice(ChoiceBase): |
| 351 |
""" |
| 352 |
A drop-down list of options. |
| 353 |
""" |
| 354 |
|
| 355 |
noneOption = ('', '') |
| 356 |
|
| 357 |
def _renderTag(self, request, key, value, converter, disabled): |
| 358 |
|
| 359 |
def renderOptions(): |
| 360 |
data = self.options |
| 361 |
if self.noneOption is not None: |
| 362 |
noneVal = iformal.IKey(self.noneOption).key() |
| 363 |
option = T.option(value=str(noneVal))[ |
| 364 |
iformal.ILabel(self.noneOption).label()] |
| 365 |
if value is None or value==str(noneVal): |
| 366 |
option = option(selected='selected') |
| 367 |
yield option |
| 368 |
if data is None: |
| 369 |
return |
| 370 |
for item in data: |
| 371 |
optValue = iformal.IKey(item).key() |
| 372 |
optLabel = iformal.ILabel(item).label() |
| 373 |
optValue = converter.fromType(optValue) |
| 374 |
option = T.option(value=str(optValue))[ |
| 375 |
iformal.ILabel(optLabel).label()] |
| 376 |
if optValue == value: |
| 377 |
option = option(selected='selected') |
| 378 |
yield option |
| 379 |
|
| 380 |
tag=T.select(name=key, id=render_cssid(key))[list(renderOptions())] |
| 381 |
if disabled: |
| 382 |
tag(class_='disabled', disabled='disabled') |
| 383 |
return tag |
| 384 |
|
| 385 |
def render(self, request, key, args, errors): |
| 386 |
converter = iformal.IStringConvertible(self.original) |
| 387 |
if errors: |
| 388 |
value = getStringFromArgs(args, key) |
| 389 |
else: |
| 390 |
value = converter.fromType(args.get(key)) |
| 391 |
return self._renderTag(request, key, value, converter, False) |
| 392 |
|
| 393 |
def renderImmutable(self, request, key, args, errors): |
| 394 |
converter = iformal.IStringConvertible(self.original) |
| 395 |
value = converter.fromType(args.get(key)) |
| 396 |
return self._renderTag(request, key, value, converter, True) |
| 397 |
|
| 398 |
|
| 399 |
@implementer(iformal.IWidget) |
| 400 |
class SelectOtherChoice(object): |
| 401 |
""" |
| 402 |
A <select> widget that includes an "Other ..." option. When the other |
| 403 |
option is selected an <input> field is enabled to allow free text entry. |
| 404 |
|
| 405 |
Unlike SelectChoice, the options items are not a (value,label) tuple |
| 406 |
because that makes no sense with the free text entry facility. |
| 407 |
|
| 408 |
TODO: |
| 409 |
* Make the Other option configurable in the JS |
| 410 |
* Refactor, refactor, refactor |
| 411 |
""" |
| 412 |
|
| 413 |
options = None |
| 414 |
noneOption = ('', '') |
| 415 |
otherOption = ('...', 'Other ...') |
| 416 |
|
| 417 |
template = None |
| 418 |
|
| 419 |
def __init__(self, original, options=None, otherOption=None): |
| 420 |
self.original = original |
| 421 |
if options is not None: |
| 422 |
self.options = options |
| 423 |
if otherOption is not None: |
| 424 |
self.otherOption = otherOption |
| 425 |
if self.template is None: |
| 426 |
self.template = nevowc.XMLFile(resource_filename('formal', |
| 427 |
'html/SelectOtherChoice.html')) |
| 428 |
|
| 429 |
|
| 430 |
def _valueFromRequestArgs(self, charset, key, args, default=''): |
| 431 |
value = getStringFromArgs(args, key, default) |
| 432 |
if value == self.otherOption[0]: |
| 433 |
value = getStringFromArgs(args, key+'-other') |
| 434 |
return value |
| 435 |
|
| 436 |
def render(self, request, key, args, errors): |
| 437 |
return self._render(request, key, args, errors, False) |
| 438 |
|
| 439 |
def renderImmutable(self, request, key, args, errors): |
| 440 |
return self._render(request, key, args, errors, True) |
| 441 |
|
| 442 |
def _render(self, request, key, args, errors, immutable): |
| 443 |
|
| 444 |
charset = "utf-8" |
| 445 |
converter = iformal.IStringConvertible(self.original) |
| 446 |
|
| 447 |
if errors: |
| 448 |
value = self._valueFromRequestArgs( |
| 449 |
charset, key, args) |
| 450 |
else: |
| 451 |
value = converter.fromType(args.get(key)) |
| 452 |
|
| 453 |
if value is None: |
| 454 |
value = iformal.IKey(self.noneOption).key() |
| 455 |
|
| 456 |
if immutable: |
| 457 |
template = nevowc.locatePattern(self.template, ['immutable']) |
| 458 |
else: |
| 459 |
template = nevowc.locatePattern(self.template, ['editable'] |
| 460 |
)["editable"] |
| 461 |
optionGen = nevowc.locatePattern(template, ['option'] |
| 462 |
)["option"] |
| 463 |
selectedOptionGen = nevowc.locatePattern(template, |
| 464 |
['selectedOption'])["selectedOption"] |
| 465 |
optionTags = [] |
| 466 |
selectOther = True |
| 467 |
|
| 468 |
if self.noneOption is not None: |
| 469 |
noneValue = iformal.IKey(self.noneOption).key() |
| 470 |
if value == noneValue: |
| 471 |
tag = selectedOptionGen.clone() |
| 472 |
selectOther = False |
| 473 |
else: |
| 474 |
tag = optionGen.clone() |
| 475 |
tag.fillSlots('value', noneValue) |
| 476 |
tag.fillSlots('label', iformal.ILabel(self.noneOption).label()) |
| 477 |
optionTags.append(tag) |
| 478 |
|
| 479 |
if self.options is not None: |
| 480 |
for item in self.options: |
| 481 |
if value == item: |
| 482 |
tag = selectedOptionGen.clone() |
| 483 |
selectOther = False |
| 484 |
else: |
| 485 |
tag = optionGen.clone() |
| 486 |
tag.fillSlots('value', item) |
| 487 |
tag.fillSlots('label', item) |
| 488 |
optionTags.append(tag) |
| 489 |
|
| 490 |
if selectOther: |
| 491 |
tag = selectedOptionGen.clone() |
| 492 |
otherValue = value |
| 493 |
else: |
| 494 |
tag = optionGen.clone() |
| 495 |
otherValue = '' |
| 496 |
tag.fillSlots('value', self.otherOption[0]) |
| 497 |
tag.fillSlots('label', self.otherOption[1]) |
| 498 |
optionTags.append(tag) |
| 499 |
|
| 500 |
tag = template |
| 501 |
tag.fillSlots('key', key) |
| 502 |
tag.fillSlots('id', render_cssid(key)) |
| 503 |
tag.fillSlots('options', optionTags) |
| 504 |
tag.fillSlots('otherValue', otherValue) |
| 505 |
return tag |
| 506 |
|
| 507 |
def processInput(self, request, key, args, default=''): |
| 508 |
charset = "utf-8" |
| 509 |
value = self._valueFromRequestArgs(charset, key, args, default) |
| 510 |
value = iformal.IStringConvertible(self.original).toType(value) |
| 511 |
if self.noneOption is not None and value == iformal.IKey(self.noneOption).key(): |
| 512 |
value = None |
| 513 |
return self.original.validate(value) |
| 514 |
|
| 515 |
|
| 516 |
@implementer( iformal.IWidget ) |
| 517 |
class RadioChoice(ChoiceBase): |
| 518 |
""" |
| 519 |
A list of options in the form of radio buttons. |
| 520 |
|
| 521 |
<div class="radiobutton"><input type="radio" ... value="..."/><label>...</label></div> |
| 522 |
""" |
| 523 |
|
| 524 |
def _renderTag(self, request, key, value, converter, disabled): |
| 525 |
|
| 526 |
def renderOption(request, itemKey, itemLabel, num, selected): |
| 527 |
cssid = render_cssid(key, num) |
| 528 |
tag = T.input(name=key, type='radio', id=cssid, |
| 529 |
value=str(itemKey)) |
| 530 |
if selected: |
| 531 |
tag = tag(checked='checked') |
| 532 |
if disabled: |
| 533 |
tag = tag(disabled='disabled') |
| 534 |
return T.div(class_='radiobutton')[ tag, T.label(for_=cssid)[itemLabel] ] |
| 535 |
|
| 536 |
def renderOptions(): |
| 537 |
# A counter to assign unique ids to each input |
| 538 |
data = self.options |
| 539 |
idCounter = itertools.count() |
| 540 |
if self.noneOption is not None: |
| 541 |
itemKey = iformal.IKey(self.noneOption).key() |
| 542 |
itemLabel = iformal.ILabel(self.noneOption).label() |
| 543 |
yield renderOption(request, itemKey, itemLabel, next(idCounter), value is None) |
| 544 |
if not data: |
| 545 |
return |
| 546 |
for item in data: |
| 547 |
itemKey = iformal.IKey(item).key() |
| 548 |
itemLabel = iformal.ILabel(item).label() |
| 549 |
itemKey = converter.fromType(itemKey) |
| 550 |
yield renderOption(request, itemKey, itemLabel, next(idCounter), itemKey==value) |
| 551 |
|
| 552 |
return T.transparent[list(renderOptions())] |
| 553 |
|
| 554 |
def render(self, request, key, args, errors): |
| 555 |
converter = iformal.IStringConvertible(self.original) |
| 556 |
if errors: |
| 557 |
value = getStringFromArgs(args, key) |
| 558 |
else: |
| 559 |
value = converter.fromType(args.get(key)) |
| 560 |
return self._renderTag(request, key, value, converter, False) |
| 561 |
|
| 562 |
def renderImmutable(self, request, key, args, errors): |
| 563 |
converter = iformal.IStringConvertible(self.original) |
| 564 |
value = converter.fromType(args.get(key)) |
| 565 |
return self._renderTag(request, key, value, converter, True) |
| 566 |
|
| 567 |
|
| 568 |
@implementer( iformal.IWidget ) |
| 569 |
class DatePartsSelect(object): |
| 570 |
""" |
| 571 |
A date entry widget that uses three <input> elements for the day, month and |
| 572 |
year parts. |
| 573 |
|
| 574 |
The default entry format is the US (month, day, year) but can be switched to |
| 575 |
the more common (day, month, year) by setting the dayFirst attribute to |
| 576 |
True. |
| 577 |
|
| 578 |
The start and end year can be passed through but default to 1970 and 2070. |
| 579 |
|
| 580 |
The months default to non-zero prefixed numerics but can be passed as a list |
| 581 |
of label, value pairs |
| 582 |
|
| 583 |
default can be whitespace-separated parts here. |
| 584 |
""" |
| 585 |
|
| 586 |
dayFirst = False |
| 587 |
days = [ (d,d) for d in range(1,32) ] |
| 588 |
months = [ (m,m) for m in range(1,13) ] |
| 589 |
yearFrom = 1970 |
| 590 |
yearTo = 2070 |
| 591 |
noneOption = ('', '') |
| 592 |
|
| 593 |
def __init__(self, original, dayFirst=None, yearFrom=None, yearTo=None, months=None, noneOption=_UNSET): |
| 594 |
self.original = original |
| 595 |
if dayFirst is not None: |
| 596 |
self.dayFirst = dayFirst |
| 597 |
if yearFrom is not None: |
| 598 |
self.yearFrom = yearFrom |
| 599 |
if yearTo is not None: |
| 600 |
self.yearTo = yearTo |
| 601 |
if months is not None: |
| 602 |
self.months = months |
| 603 |
if noneOption is not _UNSET: |
| 604 |
self.noneOption = noneOption |
| 605 |
|
| 606 |
def _namer(self, prefix): |
| 607 |
def _(part): |
| 608 |
return '%s__%s' % (prefix,part) |
| 609 |
return _ |
| 610 |
|
| 611 |
def _renderTag(self, request, year, month, day, namer, readonly): |
| 612 |
years = [(v,v) for v in range(self.yearFrom,self.yearTo)] |
| 613 |
months = self.months |
| 614 |
days = self.days |
| 615 |
|
| 616 |
options = [] |
| 617 |
if self.noneOption is not None: |
| 618 |
options.append( T.option(value=str(self.noneOption[0]))[ |
| 619 |
iformal.ILabel(self.noneOption[1]).label()] ) |
| 620 |
for value in years: |
| 621 |
if str(value[0]) == str(year): |
| 622 |
options.append( T.option(value=str(value[0]), |
| 623 |
selected='selected')[ |
| 624 |
iformal.ILabel(value[1]).label()] ) |
| 625 |
else: |
| 626 |
options.append( T.option(value=str(value)[0])[ |
| 627 |
iformal.ILabel(value[1]).label()] ) |
| 628 |
yearTag = T.select(name=namer('year'))[ options ] |
| 629 |
|
| 630 |
options = [] |
| 631 |
if self.noneOption is not None: |
| 632 |
options.append( T.option(value=str(self.noneOption[0]))[ |
| 633 |
iformal.ILabel(self.noneOption[1]).label()] ) |
| 634 |
for value in months: |
| 635 |
if str(value[0]) == str(month): |
| 636 |
options.append( T.option(value=str(value[0]), |
| 637 |
selected='selected')[ |
| 638 |
iformal.ILabel(value[1]).label()] ) |
| 639 |
else: |
| 640 |
options.append( T.option(value=str(value[0]))[ |
| 641 |
iformal.ILabel(value[1]).label()] ) |
| 642 |
monthTag = T.select(name=namer('month'))[ options ] |
| 643 |
|
| 644 |
options = [] |
| 645 |
if self.noneOption is not None: |
| 646 |
options.append( T.option(value=str(self.noneOption[0]))[ |
| 647 |
iformal.ILabel(self.noneOption[1]).label()] ) |
| 648 |
for value in days: |
| 649 |
if str(value[0]) == str(day): |
| 650 |
options.append( T.option(value=str(value[0]), |
| 651 |
selected='selected')[ |
| 652 |
iformal.ILabel(value[1]).label()] ) |
| 653 |
else: |
| 654 |
options.append( T.option(value=str(value[0]))[ |
| 655 |
iformal.ILabel(value[1]).label()] ) |
| 656 |
dayTag = T.select(name=namer('day'))[ options ] |
| 657 |
|
| 658 |
if readonly: |
| 659 |
tags = (yearTag, monthTag, dayTag) |
| 660 |
for tag in tags: |
| 661 |
tag(class_='readonly', readonly='readonly') |
| 662 |
|
| 663 |
if self.dayFirst: |
| 664 |
return dayTag, ' / ', monthTag, ' / ', yearTag, ' ', ('(day/month/year)') |
| 665 |
else: |
| 666 |
return monthTag, ' / ', dayTag, ' / ', yearTag, ' ', ('(month/day/year)') |
| 667 |
|
| 668 |
def render(self, request, key, args, errors): |
| 669 |
converter = iformal.IDateTupleConvertible(self.original) |
| 670 |
namer = self._namer(key) |
| 671 |
if errors: |
| 672 |
year = getStringFromArgs(args, namer('year').encode("ascii")) |
| 673 |
month = getStringFromArgs(args, namer('month').encode("ascii")) |
| 674 |
day = getStringFromArgs(args, namer('day').encode("ascii")) |
| 675 |
else: |
| 676 |
year, month, day = converter.fromType(args.get(key)) |
| 677 |
|
| 678 |
return self._renderTag(request, year, month, day, namer, False) |
| 679 |
|
| 680 |
def renderImmutable(self, request, key, args, errors): |
| 681 |
converter = iformal.IDateTupleConvertible(self.original) |
| 682 |
namer = self._namer(key) |
| 683 |
year, month, day = converter.fromType(args.get(key)) |
| 684 |
return self._renderTag(request, year, month, day, namer, True) |
| 685 |
|
| 686 |
def processInput(self, request, key, args, default=None): |
| 687 |
namer = self._namer(key) |
| 688 |
# Get the form field values as a (y,m,d) tuple |
| 689 |
ymd = [getStringFromArgs(args, namer(part)).strip() |
| 690 |
for part in ('year', 'month', 'day')] |
| 691 |
# Remove parts that were not entered. |
| 692 |
ymd = [p for p in ymd if p] |
| 693 |
# Nothing entered means None otherwise we need all three. |
| 694 |
if not ymd: |
| 695 |
ymd = default and default.split() |
| 696 |
elif len(ymd) != 3: |
| 697 |
raise validation.FieldValidationError("Invalid date") |
| 698 |
# So, we have what looks like a good attempt to enter a date. |
| 699 |
if ymd is not None: |
| 700 |
# Map to integers |
| 701 |
try: |
| 702 |
ymd = [int(p) for p in ymd] |
| 703 |
except ValueError: |
| 704 |
raise validation.FieldValidationError("Invalid date") |
| 705 |
ymd = iformal.IDateTupleConvertible(self.original).toType(ymd) |
| 706 |
return self.original.validate(ymd) |
| 707 |
|
| 708 |
|
| 709 |
@implementer( iformal.IWidget ) |
| 710 |
class DatePartsInput(object): |
| 711 |
""" |
| 712 |
A date entry widget that uses three <input> elements for the day, month and |
| 713 |
year parts. |
| 714 |
|
| 715 |
The default entry format is the US (month, day, year) but can be switched to |
| 716 |
the more common (day, month, year) by setting the dayFirst attribute to |
| 717 |
True. |
| 718 |
|
| 719 |
By default the widget is designed to only accept unambiguous years, i.e. |
| 720 |
the user must enter 4 character dates. |
| 721 |
|
| 722 |
Many people find it convenient or even necessary to allow a 2 character |
| 723 |
year. This can be allowed by setting the twoCharCutoffYear attribute to an |
| 724 |
integer value between 0 and 99. Anything greater than or equal to the cutoff |
| 725 |
year will be considered part of the 20th century (1900 + year); anything |
| 726 |
less the cutoff year is a 21st century (2000 + year) date. |
| 727 |
|
| 728 |
A typical twoCharCutoffYear value is 70 (i.e. 1970). However, that value is |
| 729 |
somewhat arbitrary. It's the year that time began according to the PC, but |
| 730 |
it doesn't mean much to your non-techie user. |
| 731 |
|
| 732 |
dayFirst: |
| 733 |
Make the day the first input field, i.e. day, month, year |
| 734 |
twoCharCutoffYear: |
| 735 |
Allow 2 char years and set the year where the century flips between |
| 736 |
20th and 21st century. |
| 737 |
|
| 738 |
default can be whitespace-separated parts. |
| 739 |
""" |
| 740 |
|
| 741 |
dayFirst = False |
| 742 |
twoCharCutoffYear = None |
| 743 |
|
| 744 |
def __init__(self, original, dayFirst=None, twoCharCutoffYear=None): |
| 745 |
self.original = original |
| 746 |
if dayFirst is not None: |
| 747 |
self.dayFirst = dayFirst |
| 748 |
if twoCharCutoffYear is not None: |
| 749 |
self.twoCharCutoffYear = twoCharCutoffYear |
| 750 |
|
| 751 |
def _namer(self, prefix): |
| 752 |
def _(part): |
| 753 |
return '%s__%s' % (prefix,part) |
| 754 |
return _ |
| 755 |
|
| 756 |
def _renderTag(self, request, year, month, day, namer, readonly): |
| 757 |
yearTag = T.input(type="text", name=namer('year'), |
| 758 |
value=str(year or ""), size="4") |
| 759 |
monthTag = T.input(type="text", name=namer('month'), |
| 760 |
value=str(month or ""), size="2") |
| 761 |
dayTag = T.input(type="text", name=namer('day'), |
| 762 |
value=str(day or ""), size="2") |
| 763 |
if readonly: |
| 764 |
tags = (yearTag, monthTag, dayTag) |
| 765 |
for tag in tags: |
| 766 |
tag(class_='readonly', readonly='readonly') |
| 767 |
|
| 768 |
if self.dayFirst: |
| 769 |
return dayTag, ' / ', monthTag, ' / ', yearTag, ' ', ('(day/month/year)') |
| 770 |
else: |
| 771 |
return monthTag, ' / ', dayTag, ' / ', yearTag, ' ', ('(month/day/year)') |
| 772 |
|
| 773 |
def render(self, request, key, args, errors): |
| 774 |
converter = iformal.IDateTupleConvertible(self.original) |
| 775 |
namer = self._namer(key) |
| 776 |
if errors: |
| 777 |
year = getStringFromArgs(args, namer('year').encode("ascii")) |
| 778 |
month = getStringFromArgs(args, namer('month').encode("ascii")) |
| 779 |
day = getStringFromArgs(args, namer('day').encode("ascii")) |
| 780 |
else: |
| 781 |
year, month, day = converter.fromType(args.get(key)) |
| 782 |
|
| 783 |
return self._renderTag(request, year, month, day, namer, False) |
| 784 |
|
| 785 |
def renderImmutable(self, request, key, args, errors): |
| 786 |
converter = iformal.IDateTupleConvertible(self.original) |
| 787 |
namer = self._namer(key) |
| 788 |
year, month, day = converter.fromType(args.get(key)) |
| 789 |
return self._renderTag(request, year, month, day, namer, True) |
| 790 |
|
| 791 |
def processInput(self, request, key, args, default=None): |
| 792 |
namer = self._namer(key) |
| 793 |
# Get the form field values as a (y,m,d) tuple |
| 794 |
ymd = [getStringFromArgs(args, namer(part)).strip() |
| 795 |
for part in ('year', 'month', 'day')] |
| 796 |
# Remove parts that were not entered. |
| 797 |
ymd = [p for p in ymd if p] |
| 798 |
# Nothing entered means None otherwise we need all three. |
| 799 |
if not ymd: |
| 800 |
ymd = default and default.split() |
| 801 |
elif len(ymd) != 3: |
| 802 |
raise validation.FieldValidationError("Invalid date") |
| 803 |
# So, we have what looks like a good attempt to enter a date. |
| 804 |
if ymd is not None: |
| 805 |
# If a 2-char year is allowed then prepend the century. |
| 806 |
if self.twoCharCutoffYear is not None and len(ymd[0]) == 2: |
| 807 |
try: |
| 808 |
if int(ymd[0]) >= self.twoCharCutoffYear: |
| 809 |
century = '19' |
| 810 |
else: |
| 811 |
century = '20' |
| 812 |
ymd[0] = century + ymd[0] |
| 813 |
except ValueError: |
| 814 |
pass |
| 815 |
# By now, we should have a year of at least 4 characters. |
| 816 |
if len(ymd[0]) < 4: |
| 817 |
if self.twoCharCutoffYear is not None: |
| 818 |
msg = "Please enter a 2 or 4 digit year" |
| 819 |
else: |
| 820 |
msg = "Please enter a 4 digit year" |
| 821 |
raise validation.FieldValidationError(msg) |
| 822 |
# Map to integers |
| 823 |
try: |
| 824 |
ymd = [int(p) for p in ymd] |
| 825 |
except ValueError: |
| 826 |
raise validation.FieldValidationError("Invalid date") |
| 827 |
ymd = iformal.IDateTupleConvertible(self.original).toType(ymd) |
| 828 |
return self.original.validate(ymd) |
| 829 |
|
| 830 |
|
| 831 |
@implementer( iformal.IWidget ) |
| 832 |
class MMYYDatePartsInput(object): |
| 833 |
""" |
| 834 |
Two input fields for entering the month and year. |
| 835 |
|
| 836 |
default can be a year and month separated by whitespace. |
| 837 |
""" |
| 838 |
|
| 839 |
cutoffYear = 70 |
| 840 |
|
| 841 |
def __init__(self, original, cutoffYear=None): |
| 842 |
self.original = original |
| 843 |
if cutoffYear is not None: |
| 844 |
self.cutoffYear = cutoffYear |
| 845 |
|
| 846 |
def _namer(self, prefix): |
| 847 |
def _(part): |
| 848 |
return '%s__%s' % (prefix,part) |
| 849 |
return _ |
| 850 |
|
| 851 |
def _renderTag(self, request, year, month, namer, readonly): |
| 852 |
yearTag = T.input(type="text", name=namer('year'), |
| 853 |
value=str(year), size="2") |
| 854 |
monthTag = T.input(type="text", name=namer('month'), |
| 855 |
value=str(month), size="2") |
| 856 |
if readonly: |
| 857 |
tags=(yearTag, monthTag) |
| 858 |
for tag in tags: |
| 859 |
tag(class_='readonly', readonly='readonly') |
| 860 |
return monthTag, ' / ', yearTag, ' (mm/yy)' |
| 861 |
|
| 862 |
def render(self, request, key, args, errors): |
| 863 |
converter = iformal.IDateTupleConvertible(self.original) |
| 864 |
namer = self._namer(key) |
| 865 |
if errors: |
| 866 |
year = getStringFromArgs(args, namer('year').encode("ascii")) |
| 867 |
month = getStringFromArgs(args, namer('month').encode("ascii")) |
| 868 |
# return a blank for the day |
| 869 |
day = '' |
| 870 |
else: |
| 871 |
year, month, day = converter.fromType(args.get(key)) |
| 872 |
# if we have a year as default data, stringify it and only use last two digits |
| 873 |
if year is not None: |
| 874 |
year = str(year)[2:] |
| 875 |
|
| 876 |
return self._renderTag(request, year, month, namer, False) |
| 877 |
|
| 878 |
def renderImmutable(self, request, key, args, errors): |
| 879 |
converter = iformal.IDateTupleConvertible(self.original) |
| 880 |
year, month, day = converter.fromType(args.get(key)) |
| 881 |
namer = self._namer(key) |
| 882 |
# if we have a year as default data, stringify it and only use last two digits |
| 883 |
if year is not None: |
| 884 |
year = str(year)[2:] |
| 885 |
return self._renderTag(request, year, month, namer, True) |
| 886 |
|
| 887 |
def processInput(self, request, key, args, default=None): |
| 888 |
namer = self._namer(key) |
| 889 |
value = [getStringFromArgs(args, namer(part)).strip() |
| 890 |
for part in ('year', 'month')] |
| 891 |
value = [p for p in value if p] |
| 892 |
if not value: |
| 893 |
value = default and default.split() |
| 894 |
elif len(value) != 2: |
| 895 |
raise validation.FieldValidationError("Invalid date") |
| 896 |
if value is not None: |
| 897 |
try: |
| 898 |
value = [int(p) for p in value] |
| 899 |
except ValueError: |
| 900 |
raise validation.FieldValidationError("Invalid date") |
| 901 |
if value[1] < 0 or value[1] > 99: |
| 902 |
raise validation.FieldValidationError("Invalid year. Please enter a two-digit year.") |
| 903 |
if value[0] > self.cutoffYear: |
| 904 |
value[0] = 1900 + value[0] |
| 905 |
else: |
| 906 |
value[0] = 2000 + value[0] |
| 907 |
value.append(1) |
| 908 |
value = iformal.IDateTupleConvertible(self.original).toType( value ) |
| 909 |
return self.original.validate(value) |
| 910 |
|
| 911 |
|
| 912 |
@implementer( iformal.IWidget ) |
| 913 |
class CheckboxMultiChoice(template.Element): |
| 914 |
""" |
| 915 |
Multiple choice list, rendered as a list of checkbox fields. |
| 916 |
|
| 917 |
lots enters blanks between the items (which allows a bit more |
| 918 |
flexibility in styling the stuff). |
| 919 |
|
| 920 |
emphasized can be a set of item titles that should additionally |
| 921 |
get an emphasized css class. |
| 922 |
|
| 923 |
Default is a whitespace-spearated enumeration for now. |
| 924 |
""" |
| 925 |
|
| 926 |
options = None |
| 927 |
|
| 928 |
def __init__(self, original, options=None, lots=False, |
| 929 |
emphasized=frozenset()): |
| 930 |
self.original = original |
| 931 |
self.lots = lots |
| 932 |
self.emphasized = emphasized |
| 933 |
if options is not None: |
| 934 |
self.options = options |
| 935 |
|
| 936 |
|
| 937 |
def _renderTag(self, request, key, values, converter, disabled): |
| 938 |
def _(): |
| 939 |
options = self.options |
| 940 |
# loops through checkbox options and renders |
| 941 |
for n,item in enumerate(options): |
| 942 |
optValue = iformal.IKey(item).key() |
| 943 |
optLabel = iformal.ILabel(item).label() |
| 944 |
optValue = converter.fromType(optValue) |
| 945 |
optid = render_cssid(key, n) |
| 946 |
checkbox = T.input(type='checkbox', name=key, |
| 947 |
value=str(optValue), |
| 948 |
id=optid+["-box"], class_="multichoice", |
| 949 |
onchange="Forms.Util.updateLabel(this)") |
| 950 |
if disabled: |
| 951 |
checkbox = checkbox(class_='disabled', disabled='disabled') |
| 952 |
# Label for is abominable on most browsers for this purpose. |
| 953 |
# So, let's use a span (sigh) |
| 954 |
if optValue in self.emphasized: |
| 955 |
cssCls = "multichoice emphasized" |
| 956 |
else: |
| 957 |
cssCls = "multichoice" |
| 958 |
label = T.span(class_=cssCls, id=optid+["-label"], |
| 959 |
onclick="Forms.Util.labelClick(this)")[optLabel] |
| 960 |
if optValue in values: |
| 961 |
checkbox = checkbox(checked='checked') |
| 962 |
label = label(class_=cssCls+" selected") |
| 963 |
yield T.span(class_="nobreak")[checkbox, label] |
| 964 |
if self.lots: |
| 965 |
yield " " |
| 966 |
else: |
| 967 |
yield T.br() |
| 968 |
|
| 969 |
return T.transparent[list(_())] |
| 970 |
|
| 971 |
def render(self, request, key, args, errors): |
| 972 |
|
| 973 |
converter = iformal.IStringConvertible(self.original) |
| 974 |
|
| 975 |
if errors: |
| 976 |
values = args.get(key, []) |
| 977 |
else: |
| 978 |
values = args.get(key) |
| 979 |
if values is not None: |
| 980 |
values = [converter.fromType(v) for v in values] |
| 981 |
else: |
| 982 |
values = [] |
| 983 |
|
| 984 |
return self._renderTag(request, key, values, converter, False) |
| 985 |
|
| 986 |
def renderImmutable(self, request, key, args, errors): |
| 987 |
|
| 988 |
converter = iformal.IStringConvertible(self.original) |
| 989 |
|
| 990 |
values = args.get(key) |
| 991 |
if values is not None: |
| 992 |
values = [converter.fromType(v) for v in values] |
| 993 |
else: |
| 994 |
values = [] |
| 995 |
|
| 996 |
return self._renderTag(request, key, values, converter, True) |
| 997 |
|
| 998 |
def processInput(self, request, key, args, default=''): |
| 999 |
values = [perhapsDecode(v) for v in args.get(key, default.split())] |
| 1000 |
converter = iformal.IStringConvertible(self.original) |
| 1001 |
values = [converter.toType(v) for v in values] |
| 1002 |
return self.original.validate(values) |
| 1003 |
|
| 1004 |
|
| 1005 |
@implementer( iformal.IWidget ) |
| 1006 |
class FileUpload(object): |
| 1007 |
"""NOTE: You have use something like twistedpatch.MPRequest as |
| 1008 |
your site's requestFactory to make this work. |
| 1009 |
""" |
| 1010 |
def __init__(self, original): |
| 1011 |
self.original = original |
| 1012 |
|
| 1013 |
def _renderTag(self, request, key, disabled): |
| 1014 |
tag=T.input(name=key, id=render_cssid(key),type='file') |
| 1015 |
if disabled: |
| 1016 |
tag(class_='disabled', disabled='disabled') |
| 1017 |
return tag |
| 1018 |
|
| 1019 |
def render(self, request, key, args, errors): |
| 1020 |
return self._renderTag(request, key, False) |
| 1021 |
|
| 1022 |
def renderImmutable(self, request, key, args, errors): |
| 1023 |
iformal.IFileConvertible(self.original).fromType(args.get(key)) |
| 1024 |
return self._renderTag(request, key, True) |
| 1025 |
|
| 1026 |
def processInput(self, request, key, args, default=None): |
| 1027 |
# default is ignored here. |
| 1028 |
|
| 1029 |
if key not in request.files: |
| 1030 |
return self.original.validate(None) |
| 1031 |
fileitem = request.files[key][0] |
| 1032 |
name = fileitem.file_name |
| 1033 |
if isinstance(name, bytes): |
| 1034 |
name = name.decode("utf-8", "replace") |
| 1035 |
value = (name, fileitem.file_object) |
| 1036 |
|
| 1037 |
value = iformal.IFileConvertible(self.original).fromType(value) |
| 1038 |
return self.original.validate(value) |
| 1039 |
|
| 1040 |
|
| 1041 |
class Hidden(object): |
| 1042 |
""" |
| 1043 |
A hidden form field. |
| 1044 |
""" |
| 1045 |
__implements__ = iformal.IWidget, |
| 1046 |
|
| 1047 |
inputType = 'hidden' |
| 1048 |
|
| 1049 |
def __init__(self, original): |
| 1050 |
self.original = original |
| 1051 |
|
| 1052 |
def render(self, request, key, args, errors): |
| 1053 |
if errors: |
| 1054 |
value = getStringFromArgs(args, key) |
| 1055 |
else: |
| 1056 |
value = iformal.IStringConvertible(self.original).fromType( |
| 1057 |
args.get(key)) |
| 1058 |
if value is None: |
| 1059 |
value = "" |
| 1060 |
|
| 1061 |
return T.input(type=self.inputType, name=key, id=render_cssid(key), |
| 1062 |
value=str(value)) |
| 1063 |
|
| 1064 |
def renderImmutable(self, request, key, args, errors): |
| 1065 |
return self.render(request, key, args, errors) |
| 1066 |
|
| 1067 |
def processInput(self, request, key, args, default=''): |
| 1068 |
value = getStringFromArgs(args, key, default) |
| 1069 |
value = iformal.IStringConvertible(self.original).toType(value) |
| 1070 |
return self.original.validate(value) |
| 1071 |
|
| 1072 |
|
| 1073 |
__all__ = [ |
| 1074 |
'Checkbox', 'CheckboxMultiChoice', 'CheckedPassword', |
| 1075 |
'Password', 'SelectChoice', 'TextArea', 'TextInput', 'DatePartsInput', |
| 1076 |
'DatePartsSelect', 'MMYYDatePartsInput', 'Hidden', 'RadioChoice', |
| 1077 |
'SelectOtherChoice', 'FileUpload', 'TextAreaList', |
| 1078 |
] |
| 1079 |
|