/usr/lib/python2.7/dist-packages/zope.formlib-4.3.0a2.egg-info/PKG-INFO is in python-zope.formlib 4.3.0a2-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 | Metadata-Version: 1.1
Name: zope.formlib
Version: 4.3.0a2
Summary: Form generation and validation library for Zope
Home-page: http://pypi.python.org/pypi/zope.formlib
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: .. contents::
========
Overview
========
Forms are web components that use widgets to display and input data.
Typically a template displays the widgets by accessing an attribute or
method on an underlying class.
=====
Forms
=====
Forms are web components that use widgets to display and input data.
Typically a template displays the widgets by accessing an attribute or
method on an underlying class.
This document describes some tools to assist in form development. In
the examples, we will show "forms" that are generated with simple
print statements to keep the examples simpler. Most forms will use
templates in practice.
This document starts with low-level APIs. We eventually build up to
higher-level APIs that allow forms to be defined with just a little bit
of meta data. Impatient readers may wish to skip to the later
sections, especially the section on `Helpful base classes`_. :)
A form class can define ordered collections of "form fields" using
the `Fields` constructor. Form fields are distinct from and build on
schema fields. A schema field specified attribute values. Form
fields specify how a schema field should be used in a form. The
simplest way to define a collection of form fields is by passing a
schema to the `Fields` constructor:
>>> from zope import interface, schema
>>> class IOrder(interface.Interface):
... identifier = schema.Int(title=u"Identifier", readonly=True)
... name = schema.TextLine(title=u"Name")
... min_size = schema.Float(title=u"Minimum size")
... max_size = schema.Float(title=u"Maximum size")
... color = schema.TextLine(title=u"Color", required=False)
... now = schema.Datetime(title=u"Now", readonly=True)
>>> from zope.formlib import form
>>> class MyForm:
... form_fields = form.Fields(IOrder)
This sets up a set of form fields from the interface, IOrder.
>>> len(MyForm.form_fields)
6
>>> [w.__name__ for w in MyForm.form_fields]
['identifier', 'name', 'min_size', 'max_size', 'color', 'now']
We can access individual form fields by name:
>>> MyForm.form_fields['name'].__name__
'name'
We can also select and order subsets using the select method of form fields:
>>> [w.__name__ for w in MyForm.form_fields.select('name', 'identifier')]
['name', 'identifier']
or by omitting fields:
>>> [w.__name__ for w in MyForm.form_fields.omit('now', 'identifier')]
['name', 'min_size', 'max_size', 'color']
We can omit read-only fields using the omit_readonly option when
setting up the fields:
>>> class MyForm:
... form_fields = form.Fields(IOrder, omit_readonly=True)
>>> [w.__name__ for w in MyForm.form_fields]
['name', 'min_size', 'max_size', 'color']
Getting HTML
============
Having defined form fields, we can use them to generate HTML
forms. Typically, this is done at run time by form class
instances. Let's look at an example that displays some input widgets:
>>> class MyForm:
... form_fields = form.Fields(IOrder, omit_readonly=True)
...
... def __init__(self, context, request):
... self.context, self.request = context, request
...
... def __call__(self, ignore_request=False):
... widgets = form.setUpWidgets(
... self.form_fields, 'form', self.context, self.request,
... ignore_request=ignore_request)
... return '\n'.join([w() for w in widgets])
Here we used ``form.setUpWidgets`` to create widget instances from our
form-field specifications. The second argument to ``setUpWidgets`` is a
form prefix. All of the widgets on this form are given the same
prefix. This allows multiple forms to be used within a single form
tag, assuming that each form uses a different form prefix.
Now, we can display the form:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="" />
<input class="textType" id="form.color" name="form.color" size="20"
type="text" value="" />
If the request contains any form data, that will be reflected in the
output:
>>> request.form['form.name'] = u'bob'
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="" />
<input class="textType" id="form.color" name="form.color"
size="20" type="text" value="" />
Sometimes we don't want this behavior: we want to ignore the request values,
particularly after a form has been processed and before it is drawn again.
This can be accomplished with the 'ignore_request' argument in
setUpWidgets.
>>> print(MyForm(None, request)(ignore_request=True))
... # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="" />
<input class="textType" id="form.color" name="form.color" size="20"
type="text" value="" />
Reading data
============
Of course, we don't just want to display inputs. We want to get the
input data. We can use getWidgetsData for that:
>>> from pprint import pprint
>>> class MyForm:
... form_fields = form.Fields(IOrder, omit_readonly=True)
...
... def __init__(self, context, request):
... self.context, self.request = context, request
...
... def __call__(self):
... widgets = form.setUpWidgets(
... self.form_fields, 'form', self.context, self.request)
...
... if 'submit' in self.request:
... data = {}
... errors = form.getWidgetsData(widgets, 'form', data)
... if errors:
... print('There were errors:')
... for error in errors:
... print(error)
... else:
... data = None
...
... for w in widgets:
... print(w())
... error = w.error()
... if error:
... print(error)
...
... return data
We check for a 'submit' variable in the form and, if we see it, we try
to get the data, and errors. We call `getWidgetsData`, passing:
- Our widgets
- The form prefix, and
- A data dictionary to contain input values found
The keys in the data dictionary have the form prefix stripped off.
If there are errors, we print them. When we display the widgets, we
also check for errors and show them if present. Let's add a submit
variable:
>>> request.form['form.min_size'] = u''
>>> request.form['form.max_size'] = u''
>>> request.form['submit'] = u'Submit'
>>> MyForm(None, request)() # doctest: +NORMALIZE_WHITESPACE
There were errors:
('min_size', u'Minimum size', RequiredMissing('min_size'))
('max_size', u'Maximum size', RequiredMissing('max_size'))
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="" />
<span class="error">Required input is missing.</span>
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="" />
<span class="error">Required input is missing.</span>
<input class="textType" id="form.color" name="form.color" size="20"
type="text" value="" />
{'name': u'bob'}
Note that we got an error because we omitted the values for min_size
and max size. If we provide an invalid value, we'll get an error too:
>>> request.form['form.min_size'] = u'bob'
>>> MyForm(None, request)() # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
There were errors:
(u'Invalid floating point data', ...ValueError...)
('max_size', u'Maximum size', RequiredMissing('max_size'))
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="bob" />
<span class="error">Invalid floating point data</span>
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="" />
<span class="error">Required input is missing.</span>
<input class="textType" id="form.color" name="form.color" size="20"
type="text" value="" />
{'name': u'bob'}
If we provide valid data, we'll get the data back:
>>> request.form['form.min_size'] = u'42'
>>> request.form['form.max_size'] = u'142'
>>> pprint(MyForm(None, request)(), width=1)
... # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="142.0" />
<input class="textType" id="form.color" name="form.color" size="20"
type="text" value="" />
{'max_size': 142.0,
'min_size': 42.0,
'name': u'bob'}
It's up to the form to decide what to do with the information.
Invariants
==========
The `getWidgetsData` function checks individual field constraints.
Interfaces can also provide invariants that we may also want to check.
The `checkInvariants` function can be used to do that.
In our order example, it makes sense to require that the maximum is
greater than or equal to the minimum:
>>> class IOrder(interface.Interface):
... identifier = schema.Int(title=u"Identifier", readonly=True)
... name = schema.TextLine(title=u"Name")
... min_size = schema.Float(title=u"Minimum size")
... max_size = schema.Float(title=u"Maximum size")
... now = schema.Datetime(title=u"Now", readonly=True)
...
... @interface.invariant
... def maxGreaterThanMin(order):
... if order.max_size < order.min_size:
... raise interface.Invalid("Maximum is less than Minimum")
We can update our form to check the invariant using 'checkInvariants':
>>> class MyForm:
... form_fields = form.Fields(IOrder, omit_readonly=True)
...
... def __init__(self, context, request):
... self.context, self.request = context, request
...
... def __call__(self):
... widgets = form.setUpWidgets(
... self.form_fields, 'form', self.context, self.request)
...
... if 'submit' in self.request:
... data = {}
... errors = form.getWidgetsData(widgets, 'form', data)
... invariant_errors = form.checkInvariants(
... self.form_fields, data, self.context)
... if errors:
... print('There were field errors:')
... for error in errors:
... print(error)
...
... if invariant_errors:
... print('There were invariant errors:')
... for error in invariant_errors:
... print(error)
... else:
... data = None
...
... for w in widgets:
... print(w())
... error = w.error()
... if error:
... print(error)
...
... return data
If we display the form again, we'll get the same result:
>>> pprint(MyForm(None, request)(), width=1)
... # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="142.0" />
{'max_size': 142.0,
'min_size': 42.0,
'name': u'bob'}
But if we reduce the maximum below the minimum, we'll get an invariant
error:
>>> request.form['form.min_size'] = u'42'
>>> request.form['form.max_size'] = u'14'
>>> pprint(MyForm(None, request)(), width=1)
... # doctest: +NORMALIZE_WHITESPACE
There were invariant errors:
Maximum is less than Minimum
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="14.0" />
{'max_size': 14.0,
'min_size': 42.0,
'name': u'bob'}
We can have field errors and invariant errors:
>>> request.form['form.name'] = u''
>>> pprint(MyForm(None, request)(), width=1)
... # doctest: +NORMALIZE_WHITESPACE
There were field errors:
('name', u'Name', RequiredMissing('name'))
There were invariant errors:
Maximum is less than Minimum
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="" />
<span class="error">Required input is missing.</span>
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="14.0" />
{'max_size': 14.0,
'min_size': 42.0}
If the inputs for some fields tested by invariants are missing, the
invariants are ignored:
>>> request.form['form.max_size'] = u''
>>> pprint(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
There were field errors:
('name', u'Name', RequiredMissing('name'))
('max_size', u'Maximum size', RequiredMissing('max_size'))
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="" />
<span class="error">Required input is missing.</span>
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="" />
<span class="error">Required input is missing.</span>
{'min_size': 42.0}
Edit Forms
==========
A common application of forms is edit forms. Edit forms are special
in 2 ways:
- We want to get the initial data for widgets from the object being
edited.
- If there are no errors, we want to apply the changes back to the
object being edited.
The form package provides some functions to assist with creating edit
forms. When we set up our form_fields, we use the `render_context`
option, which uses data from the context passed to setUpWidgets.
Let's create a content class that provides `IOrder` and a simple form
that uses it:
>>> import datetime
>>> @interface.implementer(IOrder)
... class Order:
...
... def __init__(self, identifier):
... self.identifier = identifier
... self.name = 'unknown'
... self.min_size = 0.0
... self.max_size = 0.0
...
... now = property(lambda self: datetime.datetime.now())
>>> order = Order(1)
>>> class MyForm:
... form_fields = form.Fields(
... IOrder, omit_readonly=True, render_context=True)
...
... def __init__(self, context, request):
... self.context, self.request = context, request
...
... def __call__(self, ignore_request=False):
... widgets = form.setUpWidgets(
... self.form_fields, 'form', self.context, self.request,
... ignore_request=ignore_request)
...
... return '\n'.join([w() for w in widgets])
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="" />
Note that, in this case, we got the values from the request, because
we used an old request. If we want to redraw the form after processing a
request, it is safest to pass ignore_request = True to setUpWidgets so that
the form is redrawn with the values as found in the object, not on the request.
>>> print(MyForm(order, request)(ignore_request=True))
... # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="unknown" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="0.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="0.0" />
If we use a new request, we will of course get the same result:
>>> request = TestRequest()
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="unknown" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="0.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="0.0" />
If we include read-only fields in an edit form, they will get display widgets:
>>> class MyForm:
... form_fields = form.Fields(IOrder, render_context=True)
... form_fields = form_fields.omit('now')
...
... def __init__(self, context, request):
... self.context, self.request = context, request
...
... def __call__(self):
... widgets = form.setUpWidgets(
... self.form_fields, 'form', self.context, self.request)
...
... return '\n'.join([w() for w in widgets])
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="unknown" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="0.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="0.0" />
When the form is submitted, we need to apply the changes back to the
object. We can use the `applyChanges` function for that:
>>> class MyForm:
... form_fields = form.Fields(IOrder, render_context=True)
... form_fields = form_fields.omit('now')
...
... def __init__(self, context, request):
... self.context, self.request = context, request
...
... def __call__(self):
... widgets = form.setUpWidgets(
... self.form_fields, 'form', self.context, self.request)
...
... if 'submit' in self.request:
... data = {}
... errors = form.getWidgetsData(widgets, 'form', data)
... invariant_errors = form.checkInvariants(
... self.form_fields, data, self.context)
... if errors:
... print('There were field errors:')
... for error in errors:
... print(error)
...
... if invariant_errors:
... print('There were invariant errors:')
... for error in invariant_errors:
... print(error)
...
... if not errors and not invariant_errors:
... changed = form.applyChanges(
... self.context, self.form_fields, data)
...
... else:
... data = changed = None
...
... for w in widgets:
... print(w())
... error = w.error()
... if error:
... print(error)
...
... if changed:
... print('Object updated')
... else:
... print('No changes')
...
... return data
Now, if we submit the form with some data:
>>> request.form['form.name'] = u'bob'
>>> request.form['form.min_size'] = u'42'
>>> request.form['form.max_size'] = u'142'
>>> request.form['submit'] = u''
>>> pprint(MyForm(order, request)(), width=1)
... # doctest: +NORMALIZE_WHITESPACE
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="142.0" />
Object updated
{'max_size': 142.0,
'min_size': 42.0,
'name': u'bob'}
>>> order.name
u'bob'
>>> order.max_size
142.0
>>> order.min_size
42.0
Note, however, that if we submit the same request, we'll see that no
changes were applied:
>>> pprint(MyForm(order, request)(), width=1)
... # doctest: +NORMALIZE_WHITESPACE
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="142.0" />
No changes
{'max_size': 142.0,
'min_size': 42.0,
'name': u'bob'}
because the new and old values are the same.
The code we included in `MyForm` above is generic: it applies to any
edit form.
Actions
=======
Our commit logic is a little complicated. It would be far more
complicated if there were multiple submit buttons.
We can use action objects to provide some distribution of application logic.
An action is an object that represents a handler for a submit button.
In the most common case, an action accepts a label and zero or more options
provided as keyword parameters:
condition
A callable or name of a method to call to test whether the action is
applicable. if the value is a method name, then the method will be
passed the action when called, otherwise, the callable will be
passed the form and the action.
validator
A callable or name of a method to call to validate and collect
inputs. This is called only if the action was submitted and if the
action either has no condition, or the condition evaluates to a true
value. If the validator is provided as a method name, the method
will be called with the action and a dictionary in which to save data.
If the validator is provided as a callable, the callable will be
called with the form, the action, and a dictionary in which to save data.
The validator normally returns a (usually empty) list of widget
input errors. It may also return None to behave as if the action
wasn't submitted.
success
A handler, called when the the action was submitted and there are no
validation errors. The handler may be provided as either a callable
or a method name. If the handler is provided as a method name, the
method will be called with the action and a dictionary containing the
form data. If the success handler is provided as a callable, the
callable will be called with the form, the action, and a dictionary
containing the data. The handler may return a form result
(e.g. page), or may return None to indicate that the form should
generate it's own output.
failure
A handler, called when the the action was submitted and there are
validation errors. The handler may be provided as either a callable
or a method name. If the handler is provided as a method name, the
method will be called with the action, a dictionary containing the form
data, and a list of errors. If the failure handler is provided as a
callable, the callable will be called with the form, the action, a
dictionary containing the data, and a list of errors. The handler
may return a form result (e.g. page), or may return None to indicate
that the form should generate it's own output.
prefix
A form prefix for the action. When generating submit actions, the
prefix should be combined with the action name, separating the two
with a dot. The default prefix is "actions"form.
name
The action name, without a prefix. If the label is a valid Python
identifier, then the lower-case label will be used, otherwise, a hex encoding
of the label will be used. If for some strange reason the labels in
a set of actions with the same prefix is not unique, a name will
have to be given for some actions to get unique names.
data
A bag of extra information that can be used by handlers, validators,
or conditions.
Let's update our edit form to use an action. We are also going to
rearrange our form quite a bit to make things more modular:
- We've created a separate `validation` method to validate inputs and
compute errors.
- We've created a `handle_edit_action` method for applying changes.
- We've created a template method for displaying the form.
Normally, this would be a ZPT template, but we just provide a Python
version here.
- We've created a call method that is described below
- We've defined a number of instance attributes for passing
information between the various methods:
- `status` is a string that, if set, is displayed at the top of the
form.
- `errors` is the set of errors found when validating.
- `widgets` is a list of set-up widgets
Here's the new version:
>>> class MyForm:
... form_fields = form.Fields(IOrder, render_context=True)
... form_fields = form_fields.omit('now')
...
... status = errors = None
... prefix = 'form'
...
... actions = form.Actions(
... form.Action('Edit', success='handle_edit_action'),
... )
...
... def __init__(self, context, request):
... self.context, self.request = context, request
...
... def validate(self, action, data):
... return (form.getWidgetsData(self.widgets, self.prefix, data) +
... form.checkInvariants(
... self.form_fields, data, self.context))
...
... def handle_edit_action(self, action, data):
... if form.applyChanges(self.context, self.form_fields, data):
... self.status = 'Object updated'
... else:
... self.status = 'No changes'
...
... def template(self):
... if self.status:
... print(self.status)
...
... result = []
...
... if self.errors:
... result.append('There were errors:')
... for error in self.errors:
... result.append(str(error))
...
... for w in self.widgets:
... result.append(w())
... error = w.error()
... if error:
... result.append(str(error))
...
... for action in self.actions:
... result.append(action.render())
...
... return '\n'.join(result)
...
... def __call__(self):
... self.widgets = form.setUpWidgets(
... self.form_fields, self.prefix, self.context, self.request)
...
... data = {}
... errors, action = form.handleSubmit(
... self.actions, data, self.validate)
... self.errors = errors
...
... if errors:
... result = action.failure(data, errors)
... elif errors is not None:
... result = action.success(data)
... else:
... result = None
...
... if result is None:
... result = self.template()
...
... return result
Lets walk through the `__call__` method.
- We set up our widgets as before.
- We use `form.handleSubmit` to validate our data. We pass the form,
actions, prefix, and `validate` method. For each action,
`form.handleSubmit` checks to see if the action was submitted. If the
action was submitted, it checks to see if it has a validator. If
the action has a validator, the action's validator is called,
otherwise the validator passed is called. The validator result (a
list of widget input errors) and the action are returned. If no
action was submitted, then `None` is returned for the errors and the
action.
- If a action was submitted and there were no errors, we call the
success method on the action. If the action has a handler defined,
it will be called and the return value is returned, otherwise None
is returned. A return value of None indicates that the form should
generate it's own result.
- If a action was submitted but there were errors, we call the
action's failure method. If the action has a failure handler
defined, it will be called and the return value is returned,
otherwise None is returned. A return value of None indicates that
the form should generate it's own result.
- No action was submitted, the result is set to None.
- If we don't have a result, we generate one with our template.
Let's try the new version of our form:
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="142.0" />
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
In this case, we didn't get any output about changes because the
request form data didn't include a submit action that matched our
action definition. Let's add one and try again:
>>> request.form['form.actions.edit'] = u''
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
No changes
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="142.0" />
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
This time, we got a status message indicating that there weren't any
changes.
Let's try changing some data:
>>> request.form['form.max_size'] = u'10/0'
>>> print(MyForm(order, request)())
... # doctest: +NORMALIZE_WHITESPACE
There were errors:
(u'Invalid floating point data',...ValueError...)
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="10/0" />
<span class="error">Invalid floating point data</span>
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
Oops, we had a typo, let's fix it:
>>> request.form['form.max_size'] = u'10.0'
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
There were errors:
Maximum is less than Minimum
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="42.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="10.0" />
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
Oh yeah, we need to reduce the minimum too: :)
>>> request.form['form.min_size'] = u'1.0'
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
Object updated
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="1.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="10.0" />
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
Ah, much better. And our order has been updated:
>>> order.max_size
10.0
>>> order.min_size
1.0
Helpful base classes
====================
Our form has a lot of repetitive code. A number of helpful base
classes provide standard form implementation.
Form
----
The `Form` base class provides a number of common attribute definitions.
It provides:
`__init__`
A constructor
`validate`
A default validation method
`__call__`
To render the form
`template`
A default template. Note that this is a NamedTemplate named "default",
so the template may also be overridden by registering an alternate
default template.
`prefix`
A string added to all widget and action names.
`setPrefix`
method for changing the prefix
`availableActions`
method for getting available actions
`adapters`
Dictionary of objects implementing each given schema
Subclasses need to:
- Provide a form_fields variable containing a list of form fields
- a actions attribute containing a list of action definitions
Subclasses may:
- Provide a label function or message id to produce
a form label.
- Override the setUpWidgets method to control how widgets are
set up. This is fairly rarely needed.
- Override the template. The form defines variables:
status
providing a short summary of the operation performed.
widgets
A collection of widgets, which can be accessed through iteration
or by name
errors
A (possibly empty) list of errors
Let's update our example to use the base class:
>>> class MyForm(form.Form):
... form_fields = form.Fields(IOrder, render_context=True)
... form_fields = form_fields.omit('now')
...
... @form.action("Edit", failure='handle_edit_action_failure')
... def handle_edit_action(self, action, data):
... if form.applyChanges(self.context, self.form_fields, data):
... self.status = 'Object updated'
... else:
... self.status = 'No changes'
...
... def handle_edit_action_failure(self, action, data, errors):
... self.status = 'There were %d errors.' % len(errors)
We inherited most of our behavior from the base class.
We also used the `action` decorator. The action decorator:
- creates an `actions` variable if one isn't already created,
- defines an action with the given label and any other arguments, and
- appends the action to the `actions` list.
The `action` decorator accepts the same arguments as the `Action`
class with the exception of the `success` option.
The creation of the `actions` is a bit magic, but provides
simplification in common cases.
Now we can try out our form:
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
No changes
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="1.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="10.0" />
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
>>> request.form['form.min_size'] = u'20.0'
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
There were 1 errors.
Invalid: Maximum is less than Minimum
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="20.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="10.0" />
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
>>> request.form['form.max_size'] = u'30.0'
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
Object updated
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="20.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="30.0" />
<input type="submit" id="form.actions.edit" name="form.actions.edit"
value="Edit" class="button" />
>>> order.max_size
30.0
>>> order.min_size
20.0
EditForm
--------
Our `handle_edit_action` action is common to edit forms. An
`EditForm` base class captures this commonality. It also sets up
widget widgets a bit differently. The `EditForm` base class sets up
widgets as if the form fields had been set up with the `render_context`
option.
>>> class MyForm(form.EditForm):
... form_fields = form.Fields(IOrder)
... form_fields = form_fields.omit('now')
>>> request.form['form.actions.apply'] = u''
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
No changes
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="20.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="30.0" />
<input type="submit" id="form.actions.apply" name="form.actions.apply"
value="Apply" class="button" />
>>> request.form['form.min_size'] = u'40.0'
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
There were errors
Invalid: Maximum is less than Minimum
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="40.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="30.0" />
<input type="submit" id="form.actions.apply" name="form.actions.apply"
value="Apply" class="button" />
>>> request.form['form.max_size'] = u'50.0'
>>> print(MyForm(order, request)())
... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
Updated on ... ... ... ...:...:...
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="40.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="50.0" />
<input type="submit" id="form.actions.apply" name="form.actions.apply"
value="Apply" class="button" />
>>> order.max_size
50.0
>>> order.min_size
40.0
Note that `EditForm` shows the date and time when content are
modified.
Multiple Schemas and Adapters
=============================
Forms can use fields from multiple schemas. This can be done in a
number of ways. For example, multiple schemas can be passed to
`form.Fields`:
>>> class IDescriptive(interface.Interface):
... title = schema.TextLine(title=u"Title")
... description = schema.TextLine(title=u"Description")
>>> class MyForm(form.EditForm):
... form_fields = form.Fields(IOrder, IDescriptive)
... form_fields = form_fields.omit('now')
In addition, if the the object being edited doesn't provide any of the
schemas, it will be adapted to the schemas it doesn't provide.
Suppose we have a generic adapter for storing descriptive information
on objects:
>>> from zope import component
>>> @component.adapter(interface.Interface)
... @interface.implementer(IDescriptive)
... class Descriptive(object):
... def __init__(self, context):
... self.context = context
...
... def title():
... def get(self):
... try:
... return self.context.__title
... except AttributeError:
... return ''
... def set(self, v):
... self.context.__title = v
... return property(get, set)
... title = title()
...
... def description():
... def get(self):
... try:
... return self.context.__description
... except AttributeError:
... return ''
... def set(self, v):
... self.context.__description = v
... return property(get, set)
... description = description()
>>> component.provideAdapter(Descriptive)
Now, we can use a single form to edit both the regular order data and
the descriptive data:
>>> request = TestRequest()
>>> print(MyForm(order, request)()) # doctest: +NORMALIZE_WHITESPACE
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="40.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="50.0" />
<input class="textType" id="form.title" name="form.title" size="20"
type="text" value="" />
<input class="textType" id="form.description" name="form.description"
size="20"
type="text" value="" />
<input type="submit" id="form.actions.apply" name="form.actions.apply"
value="Apply" class="button" />
>>> request.form['form.name'] = u'bob'
>>> request.form['form.min_size'] = u'10.0'
>>> request.form['form.max_size'] = u'20.0'
>>> request.form['form.title'] = u'Widgets'
>>> request.form['form.description'] = u'Need more widgets'
>>> request.form['form.actions.apply'] = u''
>>> myform = MyForm(order, request)
>>> print(myform())
... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
Updated on ... ... ... ...:...:...
1
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size" size="10"
type="text" value="10.0" />
<input class="textType" id="form.max_size" name="form.max_size" size="10"
type="text" value="20.0" />
<input class="textType" id="form.title" name="form.title" size="20"
type="text" value="Widgets" />
<input class="textType" id="form.description" name="form.description"
size="20"
type="text" value="Need more widgets" />
<input type="submit" id="form.actions.apply" name="form.actions.apply"
value="Apply" class="button" />
>>> order.min_size
10.0
>>> order.title #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
AttributeError: Order instance has no attribute 'title'
>>> Descriptive(order).title
u'Widgets'
Often, we'd like to get at the adapters used. If `EditForm` is used,
the adapters are available in the adapters attribute, which is a
dictionary that allows adapters to be looked up by by schema or schema
name:
>>> myform.adapters[IOrder].__class__.__name__
'Order'
>>> myform.adapters['IOrder'].__class__.__name__
'Order'
>>> myform.adapters[IDescriptive].__class__.__name__
'Descriptive'
>>> myform.adapters['IDescriptive'].__class__.__name__
'Descriptive'
If you aren't using `EditForm`, you can get a dictionary populated in
the same way by `setUpWidgets` by passing the dictionary as an
`adapters` keyword argument.
Named Widget Access
===================
The value returned from `setUpWidgets` supports named-based lookup as well as
iteration:
>>> myform.widgets['name'].__class__.__name__
'TextWidget'
>>> myform.widgets['name'].name
'form.name'
>>> myform.widgets['title'].__class__.__name__
'TextWidget'
>>> myform.widgets['title'].name
'form.title'
Form-field manipulations
========================
The form-field constructor is very flexible. We've already seen that
we can supply multiple schemas. Here are some other things you can
do.
Specifying individual fields
----------------------------
You can specify individual fields for a form. Here, we'll create a
form that collects just the name from `IOrder` and the title from
`IDescriptive`:
>>> class MyForm(form.EditForm):
... form_fields = form.Fields(IOrder['name'],
... IDescriptive['title'])
... actions = ()
>>> print(MyForm(order, TestRequest())()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.title" name="form.title" size="20"
type="text" value="Widgets" />
You can also use stand-alone fields:
>>> class MyForm(form.EditForm):
... form_fields = form.Fields(
... schema.TextLine(__name__='name', title=u"Who?"),
... IDescriptive['title'],
... )
... actions = ()
>>> print(MyForm(order, TestRequest())()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="bob" />
<input class="textType" id="form.title" name="form.title" size="20"
type="text" value="Widgets" />
But make sure the fields have a '__name__', as was done above.
Concatenating field collections
-------------------------------
It is sometimes convenient to combine multiple field collections.
Field collections support concatenation. For example, we may want to
combine field definitions:
>>> class MyExpandedForm(form.Form):
... form_fields = (
... MyForm.form_fields
... +
... form.Fields(IDescriptive['description'])
... )
... actions = ()
>>> print(MyExpandedForm(order, TestRequest())())
... # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.name" name="form.name"
size="20" type="text" value="" />
<input class="textType" id="form.title" name="form.title"
size="20" type="text" value="" />
<input class="textType" id="form.description" name="form.description"
size="20" type="text" value="" />
Using fields for display
------------------------
Normally, any writable fields get input widgets. We may want to
indicate that some fields should be used for display only. We can do
this using the `for_display` option when setting up form_fields:
>>> class MyForm(form.EditForm):
... form_fields = (
... form.Fields(IOrder, for_display=True).select('name')
... +
... form.Fields(IOrder).select('min_size', 'max_size')
... )
>>> print(MyForm(order, TestRequest())()) # doctest: +NORMALIZE_WHITESPACE
bob
<input class="textType" id="form.min_size" name="form.min_size"
size="10" type="text" value="10.0" />
<input class="textType" id="form.max_size" name="form.max_size"
size="10" type="text" value="20.0" />
<input type="submit" id="form.actions.apply" name="form.actions.apply"
value="Apply" class="button" />
Note that if all of the fields in an edit form are for display:
>>> class MyForm(form.EditForm):
... form_fields = form.Fields(IOrder, for_display=True
... ).select('name', 'min_size', 'max_size')
>>> print(MyForm(order, TestRequest())()) # doctest: +NORMALIZE_WHITESPACE
bob
10.0
20.0
we don't get an edit action. This is because the edit action defined
by `EditForm` has a condition to prevent it's use when there are no
input widgets. Check it out for an example of using action conditions.
Using fields for input
----------------------
We may want to indicate that some fields should be used for input even
if the underlying schema field is read-only. We can do this using the
`for_input` option when setting up form_fields:
>>> class MyForm(form.Form):
... form_fields = form.Fields(IOrder, for_input=True,
... render_context=True)
... form_fields = form_fields.omit('now')
...
... actions = ()
>>> print(MyForm(order, TestRequest())()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.identifier" name="form.identifier"
size="10" type="text" value="1" />
<input class="textType" id="form.name" name="form.name"
size="20" type="text" value="bob" />
<input class="textType" id="form.min_size" name="form.min_size"
size="10" type="text" value="10.0" />
<input class="textType" id="form.max_size" name="form.max_size"
size="10" type="text" value="20.0" />
Displaying or editing raw data
==============================
Sometimes, you want to display or edit data that doesn't come from an
object. One way to do this is to pass the data to setUpWidgets.
Lets look at an example:
>>> class MyForm(form.Form):
...
... form_fields = form.Fields(IOrder)
... form_fields = form_fields.omit('now')
...
... actions = ()
...
... def setUpWidgets(self, ignore_request=False):
... self.widgets = form.setUpWidgets(
... self.form_fields, self.prefix, self.context, self.request,
... data=dict(identifier=42, name=u'sally'),
... ignore_request=ignore_request
... )
In this case, we supplied initial data for the identifier and the
name. Now if we display the form, we'll see our data and defaults for
the fields we didn't supply data for:
>>> print(MyForm(None, TestRequest())()) # doctest: +NORMALIZE_WHITESPACE
42
<input class="textType" id="form.name" name="form.name"
size="20" type="text" value="sally" />
<input class="textType" id="form.min_size" name="form.min_size"
size="10" type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size"
size="10" type="text" value="" />
If data are passed in the request, they override initial data for
input fields:
>>> request = TestRequest()
>>> request.form['form.name'] = u'fred'
>>> request.form['form.identifier'] = u'0'
>>> request.form['form.max_size'] = u'100'
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
42
<input class="textType" id="form.name" name="form.name"
size="20" type="text" value="fred" />
<input class="textType" id="form.min_size" name="form.min_size"
size="10" type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size"
size="10" type="text" value="100.0" />
We'll get display fields if we ask for display fields when setting up
our form fields:
>>> class MyForm(form.Form):
...
... form_fields = form.Fields(IOrder, for_display=True)
... form_fields = form_fields.omit('now')
...
... actions = ()
...
... def setUpWidgets(self, ignore_request=False):
... self.widgets = form.setUpWidgets(
... self.form_fields, self.prefix, self.context, self.request,
... data=dict(identifier=42, name=u'sally'),
... ignore_request=ignore_request
... )
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
42
sally
<BLANKLINE>
<BLANKLINE>
Note that we didn't get data from the request because we are using all
display widgets.
Passing `ignore_request=True` to the `setUpWidgets` function ignores
the request for all values passed in the data dictionary, in order to
help with redrawing a form after a successful action handler. We'll
fake that quickly by forcing ignore_request to be `True`.
>>> class MyForm(form.Form):
...
... form_fields = form.Fields(IOrder)
... form_fields = form_fields.omit('now')
...
... actions = ()
...
... def setUpWidgets(self, ignore_request=False):
... self.widgets = form.setUpWidgets(
... self.form_fields, self.prefix, self.context, self.request,
... data=dict(identifier=42, name=u'sally'),
... ignore_request=True # =ignore_request
... )
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
42
<input class="textType" id="form.name" name="form.name"
size="20" type="text" value="sally" />
<input class="textType" id="form.min_size" name="form.min_size"
size="10" type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size"
size="10" type="text" value="" />
Specifying Custom Widgets
=========================
It is possible to use custom widgets for specific fields. This can be
done for a variety of reasons, but the provided mechanism should work
for any of them.
Custom widgets are specified by providing a widget factory that should
be used instead of the registered field view. The factory will be
called in the same way as any other field view factory, with the bound
field and the request as arguments.
Let's create a simple custom widget to use in our demonstration::
>>> import zope.formlib.widget
>>> class ISODisplayWidget(zope.formlib.widget.DisplayWidget):
...
... def __call__(self):
... return '<span class="iso-datetime">2005-05-04</span>'
To set the custom widget factory for a field, assign to the
`custom_widget` attribute of the form field object::
>>> class MyForm(form.Form):
... actions = ()
...
... form_fields = form.Fields(IOrder).select("now")
...
... # Here we set the custom widget:
...
... form_fields["now"].custom_widget = ISODisplayWidget
>>> print(MyForm(None, request)())
<span class="iso-datetime">2005-05-04</span>
Specifying Fields individually
------------------------------
All of the previous examples set up fields as collections. We can
also set up forms individually and pass them to the Fields
constructor. This is especially useful for passing options that
really only apply to a single field. The previous example can be
written more simply as:
>>> class MyForm(form.Form):
... actions = ()
...
... form_fields = form.Fields(
... form.Field(IOrder['now'], custom_widget=ISODisplayWidget),
... )
>>> print(MyForm(None, request)())
<span class="iso-datetime">2005-05-04</span>
Computing default values
------------------------
We saw earlier that we could provide initial widget data by passing a
dictionary to setUpWidgets. We can also supply a function or method
name when we set up form fields.
We might like to include the `now` field in our forms. We can provide
a function for getting the needed initial value:
>>> import datetime
>>> class MyForm(form.Form):
... actions = ()
...
... def now(self):
... return datetime.datetime(2002, 12, 2, 12, 30)
...
... form_fields = form.Fields(
... form.Fields(IOrder).omit('now'),
... form.Field(IOrder['now'], get_rendered=now),
... )
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
<BLANKLINE>
<input class="textType" id="form.name" name="form.name"
size="20" type="text" value="fred" />
<input class="textType" id="form.min_size" name="form.min_size"
size="10" type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size"
size="10" type="text" value="100.0" />
<span class="dateTime">2002 12 2 12:30:00 </span>
Now try the same with the AddFormBase which uses a setUpInputWidget:
>>> class MyAddForm(form.AddFormBase):
... actions = ()
...
... def now(self):
... return datetime.datetime(2002, 12, 2, 12, 30)
...
... form_fields = form.Fields(
... form.Fields(IOrder).omit('now'),
... form.Field(IOrder['now'], get_rendered=now),
... )
...
... def setUpWidgets(self, ignore_request=True):
... super(MyAddForm, self).setUpWidgets(ignore_request)
>>> print(MyAddForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="form.identifier" name="form.identifier"
size="10" type="text" value="" />
<input class="textType" id="form.name" name="form.name" size="20"
type="text" value="" />
<input class="textType" id="form.min_size" name="form.min_size"
size="10" type="text" value="" />
<input class="textType" id="form.max_size" name="form.max_size"
size="10" type="text" value="" />
<input class="textType" id="form.now" name="form.now" size="20"
type="text" value="2002-12-02 12:30:00" />
Note that a EditForm can't make use of a get_rendered method. The get_rendered
method does only set initial values.
Note that the function passed must take a form as an argument. The
`setUpWidgets` function takes an optional 'form' argument, which
**must** be passed if any fields use the get_rendered option. The
form base classes always pass the form to `setUpWidgets`.
Advanced Usage Hints
====================
This section documents patterns for advanced usage of the formlib package.
Multiple button groups
----------------------
Multiple button groups can be accomplished many ways, but the way we've found
that reuses the most code is the following:
>>> class MyForm(form.Form):
... form_fields = form.Fields(IOrder)
... primary_actions = form.Actions()
... secondary_actions = form.Actions()
... # can use @zope.cachedescriptors.property.Lazy for performance
... def actions(self):
... return list(self.primary_actions) + list(self.secondary_actions)
... @form.action(u'Edit', primary_actions)
... def handle_edit_action(self, action, data):
... if form.applyChanges(self.context, self.form_fields, data):
... self.status = 'Object updated'
... else:
... self.status = 'No changes'
... @form.action(u'Submit for review...', secondary_actions)
... def handle_review_action(self, action, data):
... print("do something here")
...
The template then can render the button groups separately--something like the
following, for instance:
<input tal:repeat="action view/primary_actions"
tal:replace="structure action/render"
/>
and
<input tal:repeat="action view/secondary_actions"
tal:replace="structure action/render"
/>
But the form machinery can still find the correct button. # TODO: demo
Dividing display of widget errors and invariant errors
------------------------------------------------------
Even though the form machinery only has a single errors attribute, if designers
wish to render widget errors differently than invariant errors, they can be
separated reasonably easily. The separation takes advantage of the fact that
all widget errors should implement zope.formlib.interfaces.IWidgetInputError,
and invariant errors shouldn't, because they don't come from a widget.
Therefore, a simple division such as the following should suffice.
# TODO
Omitting the form prefix
------------------------
For certain use cases (e.g. forms that post data to a different server whose
software you do not control) it is important to be able to generate forms
*without* a prefix. Using an empty string for the prefix omits it entirely.
>>> form_fields = form.Fields(IOrder).select('name')
>>> request = TestRequest()
>>> widgets = form.setUpWidgets(form_fields, '', None, request)
>>> print(widgets['name']()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="name" name="name" size="20"
type="text" value="" />
Of course, getting the widget data still works.
>>> request.form['name'] = 'foo'
>>> widgets = form.setUpWidgets(form_fields, '', None, request)
>>> data = {}
>>> form.getWidgetsData(widgets, '', data)
[]
>>> data
{'name': u'foo'}
And the value from the request is also visible in the rendered form.
>>> print(widgets['name']()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="name" name="name" size="20"
type="text" value="foo" />
The same is true when using the other setup*Widgets helpers.
>>> widgets = form.setUpInputWidgets(form_fields, '', None, request)
>>> print(widgets['name']()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="name" name="name" size="20"
type="text" value="foo" />
>>> order = Order(42)
>>> widgets = form.setUpEditWidgets(form_fields, '', order, request)
>>> print(widgets['name']()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="name" name="name" size="20"
type="text" value="foo" />
>>> widgets = form.setUpDataWidgets(form_fields, '', None, request)
>>> print(widgets['name']()) # doctest: +NORMALIZE_WHITESPACE
<input class="textType" id="name" name="name" size="20"
type="text" value="foo" />
Form actions have their own prefix in addition to the form prefix. This can be
suppressed for each action by passing the empty string as the 'prefix'
argument.
>>> class MyForm(form.Form):
...
... prefix = ''
... form_fields = form.Fields()
...
... @form.action('Button 1', name='button1')
... def handle_button1(self, action, data):
... self.status = 'Button 1 detected'
...
... @form.action('Button 2', prefix='', name='button2')
... def handle_button2(self, action, data):
... self.status = 'Button 2 detected'
...
>>> request = TestRequest()
>>> request.form['actions.button1'] = ''
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Button 1 detected
<input type="submit" id="actions.button1" name="actions.button1"
value="Button 1" class="button" />
<input type="submit" id="button2" name="button2"
value="Button 2" class="button" />
>>> request = TestRequest()
>>> request.form['button2'] = ''
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Button 2 detected
<input type="submit" id="actions.button1" name="actions.button1"
value="Button 1" class="button" />
<input type="submit" id="button2" name="button2"
value="Button 2" class="button" />
It is also possible to keep the form prefix and just suppress the 'actions' prefix.
>>> class MyForm(form.Form):
...
... form_fields = form.Fields()
...
... @form.action('Button', prefix='', name='button')
... def handle_button(self, action, data):
... self.status = 'Button detected'
...
>>> request = TestRequest()
>>> request.form['form.button'] = ''
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Button detected
<input type="submit" id="form.button" name="form.button"
value="Button" class="button" />
Additional Cases
================
Automatic Context Adaptation
----------------------------
As you may know already, the formlib will automatically adapt the context to
find a widget and data for a particular field. In an early version of
``zope.formlib``, it simply used ``field.interface`` to get the interface to
adapt to. Unfortunately, this call returns the interface the field has been
defined in and not the interface you got the field from. The following lines
demonstrate the correct behavior:
>>> import zope.interface
>>> import zope.schema
>>> class IFoo(zope.interface.Interface):
... title = zope.schema.TextLine()
>>> class IFooBar(IFoo):
... pass
Here is the unexpected behavior that caused formlib to do the wrong thing:
>>> IFooBar['title'].interface
<InterfaceClass __builtin__.IFoo>
Note: If this behavior ever changes, the formlib can be simplified again.
>>> @zope.interface.implementer(IFooBar)
... class FooBar(object):
... title = u'initial'
>>> foobar = FooBar()
>>> class Blah(object):
... def __conform__(self, iface):
... if iface is IFooBar:
... return foobar
>>> blah = Blah()
Let's now generate the form fields and instantiate the widgets:
>>> from zope.formlib import form
>>> form_fields = form.FormFields(IFooBar)
>>> request = TestRequest()
>>> widgets = form.setUpEditWidgets(form_fields, 'form', blah, request)
>>> print(widgets.get('title')())
<input class="textType" id="form.title" name="form.title"
size="20" type="text" value="initial" />
Here are some more places where the behavior was incorrect:
>>> widgets = form.setUpWidgets(form_fields, 'form', blah, request)
>>> print(widgets.get('title')())
<input class="textType" id="form.title" name="form.title"
size="20" type="text" value="" />
>>> form.checkInvariants(form_fields, {'title': 'new'}, blah)
[]
>>> form.applyChanges(blah, form_fields, {'title': 'new'})
True
Event descriptions
------------------
The ObjectModifiedEvent can be annotated with descriptions about the involved
schemas and fields. The formlib provides these annotations with the help of the
applyData function, which returns a list of modification descriptions:
>>> form.applyData(blah, form_fields, {'title': 'modified'})
{<InterfaceClass __builtin__.IFooBar>: ['title']}
The events are annotated with these descriptions. We need a subscriber to log these
infos:
>>> def eventLog(event):
... desc = event.descriptions[0]
... print('Modified:', desc.interface.__identifier__, desc.attributes)
>>> zope.event.subscribers.append(eventLog)
>>> class MyForm(form.EditForm):
... form_fields = form.FormFields(IFooBar)
>>> request = TestRequest()
>>> request.form['form.title'] = u'again modified'
>>> request.form['form.actions.apply'] = u''
>>> MyForm(FooBar(), request)()
Modified: __builtin__.IFooBar ('title',)
...
Cleanup:
>>> zope.event.subscribers.remove(eventLog)
Actions that cause a redirect
-----------------------------
When an action causes a redirect, the following `render` phase is omitted as
the result will not be displayed anyway. This is both a performance
improvement and for avoiding application bugs with one-time session
information.
>>> class MyForm(form.Form):
... form_fields = form.FormFields(IFooBar)
... @form.action("Redirect")
... def redirect(self, action, data):
... print('Action: redirect')
... self.request.response.redirect('foo')
... @form.action("Stay")
... def redirect(self, action, data):
... print('Action: stay')
... pass
... def render(self):
... print('render was called')
... return ''
>>> request = TestRequest()
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
render was called
>>> request.form['form.actions.redirect'] = u''
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Action: redirect
>>> request = TestRequest()
>>> request.form['form.actions.stay'] = u''
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Action: stay
render was called
Prevent form submit for GET requests
------------------------------------
It can be useful to only accept form submits over POST requests. This, for
example, prevents replaying data-modifying actions when reloading a page in a
web browser (most web browsers warn users for re-submitting the form when
reloading a page that was the result of a POST request). This also helps (but
is not enough by itself!) in preventing CSRF attacks.
Whenever a form component has set the ``method`` attribute on the class, it
is used when validating the form data.
>>> class MyPOSTForm(form.Form):
... method = 'POST'
...
... form_fields = form.FormFields(IFooBar)
...
... @form.action("Handle")
... def handle(self, action, data):
... print('Action: handle %s' % data)
...
... def render(self):
... return ''
This is a GET request for a form that specifies it can only validate POST
requests::
>>> request = TestRequest()
>>> request.form['form.title'] = u'Submitted Title'
>>> request.form['form.actions.handle'] = u''
>>> MyPOSTForm(None, request)() # doctest: +NORMALIZE_WHITESPACE +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
MethodNotAllowed: None, <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>
By setting the correct request method we validate input::
>>> request = TestRequest()
>>> request.method = 'POST'
>>> request.form['form.title'] = u'Submitted Title'
>>> request.form['form.actions.handle'] = u''
>>> print(MyPOSTForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Action: handle {'title': 'Submitted Title'}
Although slightly convoluted, we could require the submit to go over a
GET request::
>>> class MyGETForm(form.Form):
... method = 'GET'
...
... form_fields = form.FormFields(IFooBar)
...
... @form.action("Handle")
... def handle(self, action, data):
... print('Action: handle %s' % data)
...
... def render(self):
... return ''
>>> request = TestRequest()
>>> request.method = 'POST'
>>> request.form['form.actions.handle'] = u''
>>> MyGETForm(None, request)() # doctest: +NORMALIZE_WHITESPACE +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
MethodNotAllowed: None, <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>
>>> request = TestRequest()
>>> request.form['form.title'] = u'Submitted Title'
>>> request.form['form.actions.handle'] = u''
>>> print(MyGETForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Action: handle {'title': 'Submitted Title'}
Note how the default value for ``method`` is None, meaning all request
methods are accepted::
>>> class MyForm(form.Form):
... form_fields = form.FormFields(IFooBar)
...
... @form.action("Handle")
... def handle(self, action, data):
... print('Action: handle %s' % data)
...
... def render(self):
... return ''
>>> request = TestRequest()
>>> request.method = 'POST'
>>> request.form['form.title'] = u'Submitted Title'
>>> request.form['form.actions.handle'] = u''
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Action: handle {'title': 'Submitted Title'}
>>> request = TestRequest()
>>> request.form['form.title'] = u'Submitted Title'
>>> request.form['form.actions.handle'] = u''
>>> print(MyForm(None, request)()) # doctest: +NORMALIZE_WHITESPACE
Action: handle {'title': 'Submitted Title'}
Prevent Cross-site Request Forgery (CSRF) attacks
-------------------------------------------------
See also: http://en.wikipedia.org/wiki/Cross-site_request_forgery.
The CSRF protection in zope.formlib assumes the attacker cannot get hold of
information stored in a cookie that is send to the domain handling the form
submit. zope.formlib verifies that the token as sent with the cookie is
identical to the value as sent with the form (as a hidden input field).
zope.formlib will set a random token in the cookie when first accessing the
form. Any subsequent form rendering and submit handling will use the token
stored in this cookie.
Thus this token is reused for all forms for as long the cookie is available.
The cookie is set to expiry when the web browser quits.
This protection works best when used in combination with the afformentioned
acceptable request method restriction.
Issues to research:
* Is the name "__csrftoken__ acceptable?
* I do not see a scheme for having a token per form without keep server-
side, which I try to avoid.
* One cannot *submit* a form as the very first request to that form, as the
token will not have been set just yet. I think this acceptable.
* Tests for applications that use form components with CSRF protection
enabled, is cumbersome. Can we help that somehow?
* Is using os.urandom() for generating a token sufficient *and*
available cross-platform? Could uuid.uuid4() be an alternative?
When first visting a form, a CSRF token will be set in the cookie::
>>> class MyForm(form.Form):
... protected = True
...
... form_fields = form.FormFields(IFooBar)
...
... @form.action("Handle")
... def handle(self, action, data):
... print('Action: handle %s' % data)
>>> request = TestRequest()
>>> myform = MyForm(None, request)
>>> _ = myform() # "render" the form.
>>> csrfcookie = request.response.getCookie('__csrftoken__')
>>> csrfcookie['httponly']
True
>>> csrftoken = csrfcookie['value']
>>> csrftoken == myform.csrftoken
True
When submitting the form, the token in the cookie (that will be sent
as part of the request) needs to be identical to the value of the
hidden form field "__csrftoken__"::
>>> request = TestRequest(
... **{'HTTP_COOKIE': '__csrftoken__=%s;' % csrftoken})
>>> request.form['form.title'] = 'Submitted title'
>>> request.form['form.actions.handle'] = 'true'
>>> request.form['__csrftoken__'] = csrftoken
>>> myform = MyForm(None, request)
>>> _ = myform()
Action: handle {'title': u'Submitted title'}
If for some reason the cookie is not set, the form will raise an error::
>>> request = TestRequest(**{'HTTP_COOKIE': ''})
>>> request.form['form.title'] = 'Submitted title'
>>> request.form['form.actions.handle'] = 'true'
>>> request.form['__csrftoken__'] = csrftoken
>>> myform = MyForm(None, request)
>>> _ = myform() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
InvalidCSRFTokenError: Invalid CSRF token
As an attacker cannot read the cookie value, he can only guess the
corresponding form value, that is hard get right, so most proably wrong::
>>> request = TestRequest(
... **{'HTTP_COOKIE': '__csrftoken__=%s;' % csrftoken})
>>> request.form['form.title'] = 'Submitted title'
>>> request.form['form.actions.handle'] = 'true'
>>> request.form['__csrftoken__'] = 'a guessed value'
>>> myform = MyForm(None, request)
>>> _ = myform() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
InvalidCSRFTokenError: Invalid CSRF token
When the form value is missing altogether, the form obviously raises an error
too::
>>> request = TestRequest(
... **{'HTTP_COOKIE': '__csrftoken__=%s;' % csrftoken})
>>> request.form['form.title'] = 'Submitted title'
>>> request.form['form.actions.handle'] = 'true'
>>> myform = MyForm(None, request)
>>> _ = myform() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
InvalidCSRFTokenError: Invalid CSRF token
To repeat: this protection works as long as the cookie value is identical to
the submitted form value. No state is kept on the server. We can demonstrate
this by inventing a token value here in the test ourselves::
>>> csrftoken = 'MYNICETOKENVALUE'
>>> request = TestRequest(
... **{'HTTP_COOKIE': '__csrftoken__=%s;' % csrftoken})
>>> request.form['form.title'] = 'Submitted title'
>>> request.form['form.actions.handle'] = 'true'
>>> request.form['__csrftoken__'] = csrftoken
>>> myform = MyForm(None, request)
>>> _ = myform()
Action: handle {'title': u'Submitted title'}
It is possible to have multiple forms in one page. Of course only one of
these forms can be submitted at one point in time, but the CSRF token should
not confuse things::
>>> class FormOne(form.Form):
... prefix = 'form_one'
...
... protected = True
...
... form_fields = form.FormFields(IFooBar)
...
... @form.action("Handle")
... def handle(self, action, data):
... print('Action: handle in Form One')
>>> class FormTwo(form.Form):
... prefix = 'form_two'
...
... protected = True
...
... form_fields = form.FormFields(IFooBar)
...
... @form.action("Handle")
... def handle(self, action, data):
... print('Action: handle in Form Two')
>>> from zope.publisher.browser import BrowserPage
>>> class MultiForm(BrowserPage):
... def __init__(self, context, request):
... self.formone = FormOne(context, request)
... self.formtwo = FormTwo(context, request)
...
... def __call__(self):
... return '\n'.join((self.formone(), self.formtwo()))
...
Render the initial multi form view::
>>> request = TestRequest()
>>> multi = MultiForm(None, request)
>>> result = multi()
>>> print(result)
<input class="textType" id="form_one.title"
name="form_one.title" size="20" type="text" value="" />
<inut type="hidden" name="__csrftoken__" value="..."
<input type="submit" id="form_one.actions.handle"
name="form_one.actions.handle" value="Handle" class="button" />
<input class="textType" id="form_two.title"
name="form_two.title" size="20" type="text" value="" />
<inut type="hidden" name="__csrftoken__" value="..."
<input type="submit" id="form_two.actions.handle"
name="form_two.actions.handle" value="Handle" class="button" />
The CSRF tokens in both the hidden form fields should be identical to the one
set in the cookie::
>>> csrftoken = request.response.getCookie('__csrftoken__')['value']
>>> len(result.split(str(csrftoken)))
3
>>> multi.formone.csrftoken == multi.formtwo.csrftoken == csrftoken
True
We can indeed submit data to the forms::
>>> request = TestRequest(
... **{'HTTP_COOKIE': '__csrftoken__=%s;' % csrftoken})
>>> request.form['form_one.title'] = 'Submitted title'
>>> request.form['form_one.actions.handle'] = 'true'
>>> request.form['__csrftoken__'] = csrftoken
>>> multi = MultiForm(None, request)
>>> _ = multi()
Action: handle in Form One
>>> request = TestRequest(
... **{'HTTP_COOKIE': '__csrftoken__=%s;' % csrftoken})
>>> request.form['form_two.title'] = 'Submitted title'
>>> request.form['form_two.actions.handle'] = 'true'
>>> request.form['__csrftoken__'] = csrftoken
>>> multi = MultiForm(None, request)
>>> _ = multi()
Action: handle in Form Two
There is a view for the InvalidCSRFTokenError::
>>> from zope.component import getMultiAdapter
>>> from zope.formlib.interfaces import InvalidCSRFTokenError
>>> from zope.formlib.errors import InvalidCSRFTokenErrorView
>>> error = InvalidCSRFTokenError('Invalid CSRF token')
>>> request = TestRequest()
>>> print(InvalidCSRFTokenErrorView(error, request)())
Invalid CSRF token
===============
Browser Widgets
===============
Formlib defines widgets: views on bound schema fields. Many of these
are straightforward. For instance, see the `TextWidget` in
textwidgets.py, which is a subclass of BrowserWidget in widget.py. It
is registered as an `IBrowserRequest` view of an `ITextLine` schema
field, providing the `IInputWidget` interface::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.ITextLine"
provides="zope.formlib.interfaces.IInputWidget"
factory=".TextWidget"
permission="zope.Public"
/>
The widget then receives the field and the request as arguments to the factory
(i.e., the `TextWidget` class).
Some widgets in formlib extend this pattern. The widget registration
is extended for `Choice` fields and for the `collection` fields.
Default Choice Field Widget Registration and Lookup
===================================================
All field widgets are obtained by looking up a browser `IInputWidget`
or `IDisplayWidget` view for the field object. For `Choice` fields,
the default registered widget defers all of its behavior to the result
of another lookup: a browser widget view for the field *and* the
Choice field's vocabulary.
This allows registration of Choice widgets that differ on the basis of the
vocabulary type. For example, a widget for a vocabulary of images might have
a significantly different user interface than a widget for a vocabulary of
words. A dynamic vocabulary might implement `IIterableVocabulary` if its
contents are below a certain length, but not implement the marker "iterable"
interface if the number of possible values is above the threshhold.
This also means that choice widget factories are called with with an additional
argument. Rather than being called with the field and the request as
arguments, choice widgets receive the field, vocabulary, and request as
arguments.
Some `Choice` widgets may also need to provide a source interface,
particularly if the vocabulary is too big to iterate over.
Default Collection Field Widget Registration and Lookup
=======================================================
The default configured lookup for collection fields -- List, Tuple, and Set, for
instance -- begins with the usual lookup for a browser widget view for the
field object. This widget defers its display to the result of another lookup:
a browser widget view registered for the field and the field's `value_type`
(the type of the contained values). This allows registrations for collection
widgets that differ on the basis of the members -- a widget for entering a list
of text strings might differ significantly from a widget for entering a list of
dates...or even a list of choices, as discussed below.
This registration pattern has three implications that should be highlighted.
* First, collection fields that do not specify a `value_type` probably cannot
have a reasonable widget.
* Second, collection widgets that wish to be the default widget for a
collection with any `value_type` should be registered for the collection
field and a generic value_type: the `IField` interface. Do not register the
generic widget for the collection field only or you will break the lookup
behavior as described here.
* Third, like choice widget factories, sequence widget factories (classes or
functions) take three arguments. Typical sequence widgets receive the
field, the `value_type`, and the request as arguments.
Collections of Choices
----------------------
If a collection field's `value_type` is a `Choice` field, the second widget
again defers its behavior, this time to a third lookup based on the collection
field and the choice's vocabulary. This means that a widget for a list of
large image choices can be different than a widget for a list of small image
choices (with a different vocabulary interface), different from a widget for a
list of keyword choices, and different from a set of keyword choices.
Some advanced applications may wish to do a further lookup on the basis of the
unique attribute of the collection field--perhaps looking up a named view with
a "unique" or "lenient" token depending on the field's value, but this is not
enabled in the default Zope 3 configuration.
Registering Widgets for a New Collection Field Type
---------------------------------------------------
Because of this lookup pattern, basic widget registrations for new field types
must follow a recipe. For example, a developer may introduce a new Bag field
type for simple shopping cart functionality and wishes to add widgets for it
within the default Zope 3 collection widget registration. The bag widgets
should be registered something like this.
The only hard requirement is that the developer must register the bag + choice
widget: the widget is just the factory for the third dispatch as described
above, so the developer can use the already implemented widgets listed below::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IChoice"
provides="zope.formlib.interfaces.IDisplayWidget"
factory=".ChoiceCollectionDisplayWidget"
permission="zope.Public"
/>
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IChoice"
provides="zope.formlib.interfaces.IInputWidget"
factory=".ChoiceCollectionInputWidget"
permission="zope.Public"
/>
Beyond this, the developer may also have a generic bag widget she wishes to
register. This might look something like this, assuming there's a
`BagSequenceWidget` available in this package::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IField"
provides="zope.formlib.interfaces.IInputWidget"
factory=".BagSequenceWidget"
permission="zope.Public"
/>
Then any widgets for the bag and a vocabulary would be registered according to
this general pattern, in which `IIterableVocabulary` would be the interface of
any appropriate vocabulary and `BagWidget` is some appropriate widget::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IIterableVocabulary"
provides="zope.formlib.interfaces.IInputWidget"
factory=".BagWidget"
permission="zope.Public"
/>
Choice widgets and the missing value
====================================
Choice widgets for a non-required field include a "no value" item to allow for
not selecting any value at all. This value used to be omitted for required
fields on the assumption that the widget should avoid invalid input from the
start.
However, if the context object doesn't yet have a field value set and there's
no default value, a dropdown widget would have to select an arbitrary value
due to the way it is displayed in the browser. This way, the field would
always validate, but possibly with a value the user never chose consciously.
Starting with version zope.app.form 3.6.0, dropdown widgets for
required fields display a "no value" item even for required fields if
an arbitrary value would have to be selected by the widget otherwise.
To switch the old behaviour back on for backwards compatibility, do
zope.formlib.itemswidgets.EXPLICIT_EMPTY_SELECTION = False
during application start-up.
==============
Error handling
==============
These are a couple of functional tests that were written on-the-go ... In the
future this might become more extensive ...
Displaying invalidation errors
==============================
Validation errors, e.g. cause by invariants, are converted into readable text
by adapting them to IWidgetInputErrorView:
>>> from zope.publisher.browser import TestRequest
>>> from zope.interface.exceptions import Invalid
>>> from zope.component import getMultiAdapter
>>> from zope.formlib.interfaces import IWidgetInputErrorView
>>> error = Invalid("You are wrong!")
>>> message = getMultiAdapter((error, TestRequest()),
... IWidgetInputErrorView).snippet()
>>> message
u'<span class="error">You are wrong!</span>'
Interface invariant methods raise zope.interface.Invalid exception. Test if
this exception gets handled by the error_views.
>>> myError = Invalid('My error message')
>>> import zope.formlib.form
>>> mybase = zope.formlib.form.FormBase(None, TestRequest())
>>> mybase.errors = (myError,)
>>> save = mybase.error_views()
>>> next(save)
u'<span class="error">My error message</span>'
Now we need to set up the translation framework:
>>> from zope import component, interface
>>> from zope.i18n.interfaces import INegotiator
>>> @interface.implementer(INegotiator)
... class Negotiator:
... def getLanguage(*ignored): return 'test'
>>> component.provideUtility(Negotiator())
>>> from zope.i18n.testmessagecatalog import TestMessageFallbackDomain
>>> component.provideUtility(TestMessageFallbackDomain)
And yes, we can even handle an i18n message in an Invalid exception:
>>> from zope.i18nmessageid import MessageFactory
>>> _ = MessageFactory('my.domain')
>>> myError = Invalid(_('My i18n error message'))
>>> mybase = zope.formlib.form.FormBase(None, TestRequest())
>>> mybase.errors = (myError,)
>>> save = mybase.error_views()
>>> next(save)
u'<span class="error">[[my.domain][My i18n error message]]</span>'
Displaying widget input errors
==============================
WidgetInputError exceptions also work with i18n messages:
>>> from zope.formlib.interfaces import WidgetInputError
>>> myError = WidgetInputError(
... field_name='summary',
... widget_title=_(u'Summary'),
... errors=_(u'Foo'))
>>> mybase = zope.formlib.form.FormBase(None, TestRequest())
>>> mybase.errors = (myError,)
>>> save = mybase.error_views()
>>> next(save)
u'[[my.domain][Summary]]: <span class="error">[[my.domain][Foo]]</span>'
=======
Changes
=======
4.3.0a2 (2013-11-21)
====================
- Support for CSRF protection.
- Added support for restricting the acceptable request method for the
form submit.
4.3.0a1 (2013-02-27)
====================
- Added support for Python 3.3.
4.2.1 (2013-02-22)
==================
- Moved default values for the `BooleanDisplayWidget` from module to class
definition to make them changeable in instance.
4.2.0 (2012-11-27)
==================
- LP #1017884: Add redirect status codes (303, 307) to the set which prevent
form rendering.
- Replaced deprecated ``zope.component.adapts`` usage with equivalent
``zope.component.adapter`` decorator.
- Replaced deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Dropped support for Python 2.5.
- Make separator of ``SourceSequenceDisplayWidget`` configurable.
4.1.1 (2012-03-16)
==================
- Added `ignoreContext` attribute to form classes to control whether
`checkInvariants` takes the context of the form into account when
checking interface invariants.
By default `ignoreContext` is set to ``False``. On the `AddForm` it is
``True`` by default because the context of this form is naturally not
suitable as context for the interface invariant.
4.1.0 (2012-03-15)
==================
- `checkInvariants` now takes the context of the form into account when
checking interface invariants.
- Tests are no longer compatible with Python 2.4.
4.0.6 (2011-08-20)
==================
- Fixed bug in ``orderedSelectionList.pt`` template.
4.0.5 (2010-09-16)
==================
- Fixed Action name parameter handling, since 4.0.3 all passed names were
lowercased.
4.0.4 (2010-07-06)
==================
- Fixed tests to pass under Python 2.7.
- Fix validation of "multiple" attributes in orderedSelectionList.pt.
4.0.3 (2010-05-06)
==================
- Keep Actions from raising exceptions when passed Unicode lables [LP:528468].
- Improve display of the "nothing selected" case for optional Choice fields
[LP:269782].
- Improve truth testing for ItemDisplayWidget [LP:159232].
- Don't blow up if TypeError raised during token conversion [LP:98491].
4.0.2 (2010-03-07)
==================
- Adapted tests for Python 2.4 (enforce sorting for short pprint output)
4.0.1 (2010-02-21)
==================
- Documentation uploaded to PyPI now contains widget documentation.
- Escape MultiCheckBoxWidget content [LP:302427].
4.0 (2010-01-08)
================
- Widget implementation and all widgets from zope.app.form have been
moved into zope.formlib, breaking zope.formlib's dependency on
zope.app.form (instead zope.app.form now depends on zope.formlib).
Widgets can all be imported from ``zope.formlib.widgets``.
Widget base classes and render functionality is in
``zope.formlib.widget``.
All relevant widget interfaces are now in ``zope.formlib.interfaces``.
3.10.0 (2009-12-22)
===================
- Use named template from zope.browserpage in favor of zope.app.pagetemplate.
3.9.0 (2009-12-22)
==================
- Use ViewPageTemplateFile from zope.browserpage.
3.8.0 (2009-12-22)
==================
- Adjusted test output to new zope.schema release.
3.7.0 (2009-12-18)
==================
- Rid ourselves from zope.app test dependencies.
- Fix: Button label needs escaping
3.6.0 (2009-05-18)
==================
- Remove deprecated imports.
- Remove dependency on zope.app.container (use ``IAdding`` from
``zope.browser.interfaces``) instead. Depend on
``zope.browser>=1.1`` (the version with ``IAdding``).
- Moved ``namedtemplate`` to ``zope.app.pagetemplate``, to cut some
dependencies on ``zope.formlib`` when using this feature. Left BBB
imports here.
3.5.2 (2009-02-21)
==================
- Adapt tests for Python 2.5 output.
3.5.1 (2009-01-31)
==================
- Adapt tests to upcoming zope.schema release 3.5.1.
3.5.0 (2009-01-26)
==================
New Features
------------
- Test dependencies are declared in a `test` extra now.
- Introduced ``zope.formlib.form.applyData`` which works like
``applyChanges`` but returns a dictionary with information about
which attribute of which schema changed. This information is then
sent along with the ``IObjectModifiedEvent``.
This fixes https://bugs.launchpad.net/zope3/+bug/98483.
Bugs Fixed
----------
- Actions that cause a redirect (301, 302) do not cause the `render` method to
be called anymore.
- The zope.formlib.form.Action class didn't fully implement
zope.formlib.interfaces.IAction.
- zope.formlib.form.setupWidgets and zope.formlib.form.setupEditWidgets did
not check for write access on the adapter but on context. This fixes
https://bugs.launchpad.net/zope3/+bug/219948
3.4.0 (2007-09-28)
==================
No further changes since 3.4.0a1.
3.4.0a1 (2007-04-22)
====================
Initial release as a separate project, corresponds to zope.formlib
from Zope 3.4.0a1
Keywords: zope3 form widget
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Framework :: Zope3
|