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
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163 | # -*- coding: utf-8 -*-
""" A Pyramid app that demonstrates various Deform widgets and
capabilities and which provides a functional test suite """
import csv
import decimal
import inspect
import logging
import pprint
import random
import sys
import colander
from pyramid.config import Configurator
from pyramid.i18n import TranslationStringFactory
from pyramid.i18n import get_locale_name
from pyramid.i18n import get_localizer
from pyramid.renderers import get_renderer
from pyramid.response import Response
from pyramid.session import SignedCookieSessionFactory
from pyramid.threadlocal import get_current_request
from pyramid.view import view_config
from pyramid.view import view_defaults
import deform
from deform.renderer import configure_zpt_renderer
from iso8601 import iso8601
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import PythonLexer
log = logging.getLogger(__name__)
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
PY3 = sys.version_info[0] == 3
PY38MIN = sys.version_info[0] == 3 and sys.version_info[1] >= 8
if PY3:
def unicode(val, encoding="utf-8"):
return val
_ = TranslationStringFactory("deformdemo")
formatter = HtmlFormatter(nowrap=True)
css = formatter.get_style_defs()
# the zpt_renderer above is referred to within the demo.ini file by dotted name
class demonstrate(object):
def __init__(self, title):
self.title = title
def __call__(self, method):
method.demo = self.title
return method
# Py2/Py3 compat
# http://stackoverflow.com/a/16888673/315168
# eliminate u''
def my_safe_repr(obj, context, maxlevels, level, sort_dicts=True):
if type(obj) == unicode:
obj = obj.encode("utf-8")
# Python 3.8 changed the call signature of pprint._safe_repr.
# by adding sort_dicts.
if PY38MIN:
return pprint._safe_repr(obj, context, maxlevels, level, sort_dicts)
else:
return pprint._safe_repr(obj, context, maxlevels, level)
@view_defaults(route_name="deformdemo")
class DeformDemo(object):
def __init__(self, request):
self.request = request
self.macros = get_renderer("templates/main.pt").implementation().macros
def render_form(
self,
form,
appstruct=colander.null,
submitted="submit",
success=None,
readonly=False,
is_i18n=False,
):
captured = None
if submitted in self.request.POST:
# the request represents a form submission
try:
# try to validate the submitted values
controls = self.request.POST.items()
captured = form.validate(controls)
if success:
response = success()
if response is not None:
return response
html = form.render(captured)
except deform.ValidationFailure as e:
# the submitted values could not be validated
html = e.render()
else:
# the request requires a simple form rendering
html = form.render(appstruct, readonly=readonly)
if self.request.is_xhr:
return Response(html)
code, start, end = self.get_code(2)
locale_name = get_locale_name(self.request)
reqts = form.get_widget_resources()
printer = pprint.PrettyPrinter()
printer.format = my_safe_repr
output = printer.pformat(captured)
captured = highlight(output, PythonLexer(), formatter)
# values passed to template for rendering
return {
"form": html,
"captured": captured,
"code": code,
"start": start,
"end": end,
"is_i18n": is_i18n,
"locale": locale_name,
"demos": self.get_demos(),
"title": self.get_title(),
"css_links": reqts["css"],
"js_links": reqts["js"],
}
def get_code(self, level):
frame = sys._getframe(level)
lines, start = inspect.getsourcelines(frame.f_code)
end = start + len(lines)
code = "".join(lines)
if not PY3:
code = unicode(code, "utf-8")
return highlight(code, PythonLexer(), formatter), start, end
@view_config(name="thanks.html")
def thanks(self):
return Response(
"<html><body><p>Thanks!</p><small>"
'<a href="..">Up</a></small></body></html>'
)
@view_config(name="allcode", renderer="templates/code.pt")
def allcode(self):
params = self.request.params
start = params.get("start")
end = params.get("end")
hl_lines = None
if start and end:
start = int(start)
end = int(end)
hl_lines = list(range(start, end))
code = open(inspect.getsourcefile(self.__class__), "r").read()
code = code.encode("utf-8")
formatter = HtmlFormatter(
linenos="table",
lineanchors="line",
cssclass="hightlight ",
hl_lines=hl_lines,
)
html = highlight(code, PythonLexer(), formatter)
return {"code": html, "demos": self.get_demos()}
def get_title(self):
# gross hack; avert your eyes
frame = sys._getframe(3)
attr = frame.f_locals["attr"]
inst = frame.f_locals["inst"]
method = getattr(inst, attr)
return method.demo
@view_config(name="pygments.css")
def cssview(self):
response = Response(body=css, content_type="text/css")
response.cache_expires = 360
return response
@view_config(renderer="templates/index.pt")
def index(self):
return {"demos": self.get_demos()}
def get_demos(self):
def predicate(value):
if getattr(value, "demo", None) is not None:
return True
demos = inspect.getmembers(self, predicate)
L = []
for name, method in demos:
url = self.request.resource_url(
self.request.root, name, route_name="deformdemo"
)
L.append((method.demo, url))
L.sort()
return L
@view_config(renderer="templates/form.pt", name="textinput")
@demonstrate("Text Input Widget")
def textinput(self):
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=deform.widget.TextInputWidget(),
description="Enter some text",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="textinput_with_html5")
@demonstrate("Text Input Widget (with arbitrary HTML5 attributes)")
def textinput_with_html5(self):
class Schema(colander.Schema):
hours_worked = colander.SchemaNode(
colander.Decimal(),
description="Enter number of hours worked",
default=30.00,
validator=colander.Range(min=0, max=decimal.Decimal("99.99")),
widget=deform.widget.TextInputWidget(
attributes={
"type": "number",
"inputmode": "decimal",
"step": "0.01",
"min": "0",
"max": "99.99",
}
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="textinput_with_css_class")
@demonstrate("Text Input Widget (with CSS class)")
def textinput_with_css_class(self):
css_widget = deform.widget.TextInputWidget(
css_class="deform-widget-with-style"
)
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=css_widget,
description="Enter some text",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="textinput_readonly")
@demonstrate("Text Input Widget (read-only)")
def textinput_readonly(self):
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(readonly=True),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"text": "text"})
@view_config(renderer="templates/form.pt", name="money_input")
@demonstrate("Money Input")
def money_input(self):
widget = deform.widget.MoneyInputWidget(options={"allowZero": True})
class Schema(colander.Schema):
greenbacks = colander.SchemaNode(
colander.Decimal(),
widget=widget,
description="Enter some money",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="autocomplete_input")
@demonstrate("Autocomplete Input Widget")
def autocomplete_input(self):
choices = ["bar", "baz", "two", "three", "foo & bar", "one < two"]
widget = deform.widget.AutocompleteInputWidget(
values=choices, min_length=1
)
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=widget,
description='Enter some text (Hint: try "b" or "t")',
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="autocomplete_remote_input"
)
@demonstrate("Autocomplete Input Widget (with Remote Data Source)")
def autocomplete_remote_input(self):
widget = deform.widget.AutocompleteInputWidget(
min_length=1,
values=self.request.route_path(
"deformdemo", traverse=("autocomplete_input_values",)
),
)
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=widget,
description='Enter some text (Hint: try "b" or "t")',
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="json", name="autocomplete_input_values")
def autocomplete_input_values(self):
text = self.request.params.get("term", "")
return [
x
for x in ["bar", "baz", "two", "three", "foo & bar", "one < two"]
if x.startswith(text)
]
@view_config(renderer="templates/form.pt", name="textarea")
@demonstrate("Text Area Widget")
def textarea(self):
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=deform.widget.TextAreaWidget(rows=10, cols=60),
description="Enter some text",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="textarea_readonly")
@demonstrate("Text Area Widget (read-only)")
def textarea_readonly(self):
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=deform.widget.TextAreaWidget(readonly=True),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"text": "text"})
@view_config(renderer="templates/form.pt", name="richtext")
@demonstrate("Rich Text Widget (TinyMCE)")
def richtext(self):
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
# These options are directly passed to underylying TinyMCE as
# browser_spellcheck : true
# See https://www.tinymce.com/docs/configure/
widget=deform.widget.RichTextWidget(
options=(("browser_spellcheck", True),)
),
description="Enter some text",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="richtext_i18n")
@demonstrate("Rich Text Widget (internationalized)")
def richtext_i18n(self):
locale_name = get_locale_name(self.request)
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
widget=deform.widget.RichTextWidget(),
description=_("Enter some text"),
)
_LOCALE_ = colander.SchemaNode(
colander.String(),
widget=deform.widget.HiddenWidget(),
default=locale_name,
)
schema = Schema()
form = deform.Form(
schema, buttons=[deform.Button("submit", _("Submit"))]
)
return self.render_form(form, is_i18n=True)
@view_config(renderer="templates/form.pt", name="delayed_richtext")
@demonstrate("Rich Text Widget (delayed)")
def delayed_richtext(self):
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
widget=deform.widget.RichTextWidget(delayed_load=True),
description="Enter some text",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="richtext_readonly")
@demonstrate("Rich Text Widget (read-only)")
def richtext_readonly(self):
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
widget=deform.widget.RichTextWidget(readonly=True),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"text": "<p>Hi!</p>"})
@view_config(renderer="templates/form.pt", name="password")
@demonstrate("Password Widget")
def password(self):
class Schema(colander.Schema):
password = colander.SchemaNode(
colander.String(),
validator=colander.Length(min=5, max=100),
widget=deform.widget.PasswordWidget(),
description="Enter a password",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="password_redisplay")
@demonstrate("Password Widget (redisplay on validation failure)")
def password_redisplay(self):
class Schema(colander.Schema):
password = colander.SchemaNode(
colander.String(),
validator=colander.Length(min=5, max=100),
widget=deform.widget.PasswordWidget(redisplay=True),
description="Enter a password",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkbox")
@demonstrate("Checkbox Widget")
def checkbox(self):
class Schema(colander.Schema):
want = colander.SchemaNode(
colander.Boolean(),
description="Check this box!",
widget=deform.widget.CheckboxWidget(),
title="I Want It!",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/popup_example.pt", name="popup")
@demonstrate("Popup and retail rendering")
def popup(self):
"""Render a page (``popup_example.pt``) that contains
a specially styled form (``modal.pt``).
.. note ::
Pop up form templates are NOT supplied with Deform core.
They are in the deformdemo package for demostration purposes.
You can copy them to your own project and configure
widget template paths.
popup_example.pt contains the page HTML template.
Javascript: The JavaScript logic to show and hide the pop up is
in ``poup_example.pt``.
We need to automatically open the pop up on a validation error.
Template registration: See ``deformdemo.main`` how we register a
template path ``custom_widgets`` where the custom form template lies.
See also :ref:`templates` in Deform documentation for more information.
Source code:
https://github.com/Pylons/deformdemo/blob/main/deformdemo/templates/popup_example.pt
https://github.com/Pylons/deformdemo/blob/main/deformdemo/custom_widgets/modal.pt
"""
class Schema(colander.Schema):
title = "Pop up example title"
# Override default form.pt for rendering <form>
widget = deform.widget.FormWidget(template="modal.pt")
name = colander.SchemaNode(
colander.String(), description="Enter your name (required)"
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
# CSS is used in <button> opener and JS code
form.formid = "my-pop-up"
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkbox_with_label")
@demonstrate("Checkbox Widget (with Label)")
def checkbox_with_label(self):
class Schema(colander.Schema):
want = colander.SchemaNode(
colander.Boolean(),
description="Check this box!",
widget=deform.widget.CheckboxWidget(),
label="Really",
title="I Want It!",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkbox_readonly")
@demonstrate("Checkbox Widget (read-only)")
def checkbox_readonly(self):
class Schema(colander.Schema):
want = colander.SchemaNode(
colander.Boolean(),
description="Check this box!",
widget=deform.widget.CheckboxWidget(readonly=True),
title="I Want It!",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"want": True})
@view_config(renderer="templates/form.pt", name="radiochoice")
@demonstrate("Radio Choice Widget")
def radiochoice(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
validator=colander.OneOf([x[0] for x in choices]),
widget=deform.widget.RadioChoiceWidget(values=choices),
title="Choose your pepper",
description="Select a Pepper",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="radiochoice_inline")
@demonstrate("Radio Choice Widget (inline)")
def radiochoice_inline(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
validator=colander.OneOf([x[0] for x in choices]),
widget=deform.widget.RadioChoiceWidget(
values=choices, inline=True
),
title="Choose your pepper",
description="Select a Pepper",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="radiochoice_int")
@demonstrate("Radio Choice Widget (with int values)")
def radiochoice_int(self):
choices = ((0, "Habanero"), (1, "Jalapeno"), (2, "Chipotle"))
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Int(),
validator=colander.OneOf([x[0] for x in choices]),
widget=deform.widget.RadioChoiceWidget(values=choices),
title="Choose your pepper",
description="Select a Pepper",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="radiochoice_readonly")
@demonstrate("Radio Choice Widget (read-only)")
def radiochoice_readonly(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.RadioChoiceWidget(
values=choices, readonly=True
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"pepper": "jalapeno"})
@view_config(renderer="templates/form.pt", name="checkedinput")
@demonstrate("Checked Input Widget")
def checkedinput(self):
widget = deform.widget.CheckedInputWidget(
subject="Email", confirm_subject="Confirm Email"
)
class Schema(colander.Schema):
email = colander.SchemaNode(
colander.String(),
title="Email Address",
description="Type your email address and confirm it",
validator=colander.Email(),
widget=widget,
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkedinput_readonly")
@demonstrate("Checked Input Widget (read-only)")
def checkedinput_readonly(self):
widget = deform.widget.CheckedInputWidget(
subject="Email", confirm_subject="Confirm Email", readonly=True
)
class Schema(colander.Schema):
email = colander.SchemaNode(
colander.String(),
title="Email Address",
description="Type your email address and confirm it",
validator=colander.Email(),
widget=widget,
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"email": "ww@graymatter.com"})
@view_config(renderer="templates/form.pt", name="checkedpassword")
@demonstrate("Checked Password Widget")
def checkedpassword(self):
class Schema(colander.Schema):
password = colander.SchemaNode(
colander.String(),
validator=colander.Length(min=5),
widget=deform.widget.CheckedPasswordWidget(),
description="Type your password and confirm it",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="checkedpassword_redisplay"
)
@demonstrate("Checked Password Widget (redisplay on validation failure)")
def checkedpassword_redisplay(self):
class Schema(colander.Schema):
password = colander.SchemaNode(
colander.String(),
validator=colander.Length(min=5),
widget=deform.widget.CheckedPasswordWidget(redisplay=True),
description="Type your password and confirm it",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkedpassword_readonly")
@demonstrate("Checked Password Widget (read-only)")
def checkedpassword_readonly(self):
class Schema(colander.Schema):
password = colander.SchemaNode(
colander.String(),
validator=colander.Length(min=5),
widget=deform.widget.CheckedPasswordWidget(readonly=True),
description="Type your password and confirm it",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"password": "foo"})
@view_config(renderer="templates/form.pt", name="checkedinput_withmask")
@demonstrate("Checked Input Widget (with Input Mask)")
def checkedinput_withmask(self):
widget = deform.widget.CheckedInputWidget(
subject="SSN",
confirm_subject="Confirm SSN",
mask="999-99-9999",
mask_placeholder="#",
)
class Schema(colander.Schema):
ssn = colander.SchemaNode(
colander.String(),
widget=widget,
title="Social Security Number",
description="Type your Social Security Number and confirm it",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="dynamic_field")
@demonstrate("Dynamic fields: add and remove")
def dynamic_field(self):
class Schema(colander.Schema):
field1 = colander.SchemaNode(
colander.String(),
title="Field 1",
description="Add ?nofield1 to URL to delete this field",
)
field2 = colander.SchemaNode(
colander.String(),
title="Field 2",
description="May or may not appear. Hit refresh.",
)
def after_bind(self, schema, kwargs):
# after_bind() can be used as subclass method
# or a parameter passed to schema constructor.
#
# When schema is bound you are free to post-process any fields:
# Hide fields, change widgets or dynamically add more fields.
# You can read request, request.session and other variables
# here to fulfill conditions.
#
# More abount binding:
#
# http://docs.pylonsproject.org/projects/colander/en/latest/binding.html
#
# http://docs.pylonsproject.org/projects/colander/en/latest/binding.html#after-bind
#
request = kwargs["request"]
if "nofield1" in request.params:
del self["field1"]
if random.random() < 0.5:
del self["field2"]
# Dynamically add new field
self["field3"] = colander.SchemaNode(
colander.String(),
title="Field 3",
description="Dynamically created",
)
schema = Schema()
schema = schema.bind(request=self.request)
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="mapping")
@demonstrate("Mapping Widget")
def mapping(self):
class Mapping(colander.Schema):
name = colander.SchemaNode(
colander.String(), description="Content name"
)
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DatePartsWidget(),
description="Content date",
)
class Schema(colander.Schema):
number = colander.SchemaNode(colander.Integer())
mapping = Mapping()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="mapping_accordion")
@demonstrate("Accordion")
def mapping_accordion(self):
"""A section of form can be hidden by using Bootstrap 3 accordions.
On field errors accordions are always forced to open.
See ``deform/static/form.css`` for chevron styling.
http://getbootstrap.com/javascript/#collapse
"""
class Mapping(colander.Schema):
name = colander.SchemaNode(
colander.String(), description="Content name"
)
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DatePartsWidget(),
description="Content date",
)
class Schema(colander.Schema):
number = colander.SchemaNode(colander.Integer())
mapping = Mapping(
title="Open by default",
widget=deform.widget.MappingWidget(
template="mapping_accordion", open=True
),
)
mapping2 = Mapping(
title="Closed by default",
widget=deform.widget.MappingWidget(
template="mapping_accordion", open=False
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="ajaxform")
@demonstrate("AJAX form submission (inline success)")
def ajaxform(self):
class Mapping(colander.Schema):
name = colander.SchemaNode(
colander.String(), description="Content name"
)
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DatePartsWidget(),
description="Content date",
)
class Schema(colander.Schema):
number = colander.SchemaNode(colander.Integer())
mapping = Mapping()
richtext = colander.SchemaNode(
colander.String(), widget=deform.widget.RichTextWidget()
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",), use_ajax=True)
def succeed():
return Response('<div id="thanks">Thanks!</div>')
return self.render_form(form, success=succeed)
@view_config(renderer="templates/form.pt", name="ajaxform_redirect")
@demonstrate("AJAX form submission (redirect on success)")
def ajaxform_redirect(self):
class Mapping(colander.Schema):
name = colander.SchemaNode(
colander.String(), description="Content name"
)
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DatePartsWidget(),
description="Content date",
)
class Schema(colander.Schema):
number = colander.SchemaNode(colander.Integer())
mapping = Mapping()
schema = Schema()
options = """
{success:
function (rText, sText, xhr, form) {
var loc = xhr.getResponseHeader('X-Relocate');
if (loc) {
document.location = loc;
};
}
}
"""
def succeed():
location = self.request.resource_url(
self.request.root, "thanks.html", route_name="deformdemo"
)
# To appease jquery 1.6+, we need to return something that smells
# like HTML, or we get a "Node cannot be inserted at the
# specified point in the hierarchy" Javascript error. This didn't
# used to be required under JQuery 1.4.
return Response(
"<div>hurr</div>",
headers=[
("X-Relocate", location),
("Content-Type", "text/html"),
],
)
form = deform.Form(
schema, buttons=("submit",), use_ajax=True, ajax_options=options
)
return self.render_form(form, success=succeed)
@view_config(renderer="templates/form.pt", name="sequence_of_radiochoices")
@demonstrate("Sequence of Radio Choice Widgets")
def sequence_of_radiochoices(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Peppers(colander.SequenceSchema):
pepper = colander.SchemaNode(
colander.String(),
validator=colander.OneOf([x[0] for x in choices]),
widget=deform.widget.RadioChoiceWidget(values=choices),
title="Pepper Chooser",
description="Select a Pepper",
)
class Schema(colander.Schema):
peppers = Peppers()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="sequence_of_autocompletes"
)
@demonstrate("Sequence of Autocomplete Widgets")
def sequence_of_autocompletes(self):
choices = ["bar", "baz", "two", "three"]
widget = deform.widget.AutocompleteInputWidget(values=choices)
class Sequence(colander.SequenceSchema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=widget,
description='Enter some text (Hint: try "b" or "t")',
)
class Schema(colander.Schema):
texts = Sequence()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="sequence_of_dateinputs")
@demonstrate("Sequence of Date Inputs")
def sequence_of_dateinputs(self):
import datetime
class Sequence(colander.SequenceSchema):
date = colander.SchemaNode(
colander.Date(),
validator=colander.Range(
min=datetime.date(2010, 5, 5),
min_err=_("${val} is earlier than earliest date ${min}"),
),
)
class Schema(colander.Schema):
dates = Sequence()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="sequence_of_i18n")
@demonstrate("Sequence of I18N")
def sequence_of_i18n(self):
import datetime
locale_name = get_locale_name(self.request)
class Sequence(colander.SequenceSchema):
date = colander.SchemaNode(
colander.Date(),
title=_("Event date"),
validator=colander.Range(
min=datetime.date(2010, 5, 5),
min_err=_("${val} is earlier than earliest date ${min}"),
),
)
class Schema(colander.Schema):
dates = Sequence(title=_("Dates"))
_LOCALE_ = colander.SchemaNode(
colander.String(),
widget=deform.widget.HiddenWidget(),
default=locale_name,
)
schema = Schema()
form = deform.Form(
schema, buttons=[deform.Button("submit", _("Submit"))]
)
return self.render_form(form, is_i18n=True)
@view_config(renderer="templates/form.pt", name="sequence_of_richtext")
@demonstrate("Sequence of Rich Text Widgets")
def sequence_of_richtext(self):
class Sequence(colander.SequenceSchema):
text = colander.SchemaNode(
colander.String(),
widget=deform.widget.RichTextWidget(),
description="Enter some text",
)
class Schema(colander.Schema):
texts = Sequence()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="sequence_of_masked_textinputs"
)
@demonstrate("Sequence of Masked Text Inputs")
def sequence_of_masked_textinputs(self):
class Sequence(colander.SequenceSchema):
text = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(mask="999-99-9999"),
)
class Schema(colander.Schema):
texts = Sequence()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="sequence_of_fileuploads")
@demonstrate("Sequence of File Upload Widgets")
def sequence_of_fileuploads(self):
class Sequence(colander.SequenceSchema):
upload = colander.SchemaNode(
deform.FileData(),
widget=deform.widget.FileUploadWidget(tmpstore),
)
class Schema(colander.Schema):
uploads = Sequence()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, success=tmpstore.clear)
@view_config(
renderer="templates/form.pt",
name="sequence_of_fileuploads_with_initial_item",
)
@demonstrate("Sequence of File Upload Widgets (with Initial Item)")
def sequence_of_fileuploads_with_initial_item(self):
class Sequence(colander.SequenceSchema):
upload = colander.SchemaNode(
deform.FileData(),
widget=deform.widget.FileUploadWidget(tmpstore),
)
class Schema(colander.Schema):
uploads = Sequence()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
form["uploads"].widget = deform.widget.SequenceWidget(min_len=1)
return self.render_form(form, success=tmpstore.clear)
@view_config(renderer="templates/form.pt", name="sequence_of_mappings")
@demonstrate("Sequence of Mapping Widgets")
def sequence_of_mappings(self):
class Person(colander.Schema):
name = colander.SchemaNode(colander.String())
age = colander.SchemaNode(
colander.Integer(), validator=colander.Range(0, 200)
)
class People(colander.SequenceSchema):
person = Person()
class Schema(colander.Schema):
people = People()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt",
name="sequence_of_mappings_with_initial_item",
)
@demonstrate("Sequence of Mapping Widgets (with Initial Item)")
def sequence_of_mappings_with_initial_item(self):
class Person(colander.Schema):
name = colander.SchemaNode(colander.String())
age = colander.SchemaNode(
colander.Integer(), validator=colander.Range(0, 200)
)
class People(colander.SequenceSchema):
person = Person()
class Schema(colander.Schema):
people = People()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
form["people"].widget = deform.widget.SequenceWidget(min_len=1)
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="readonly_sequence_of_mappings"
)
@demonstrate("Sequence of Mappings (read-only)")
def readonly_sequence_of_mappings(self):
class Person(colander.Schema):
name = colander.SchemaNode(colander.String())
age = colander.SchemaNode(
colander.Integer(), validator=colander.Range(0, 200)
)
class People(colander.SequenceSchema):
person = Person()
class Schema(colander.Schema):
people = People()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(
form,
appstruct={
"people": [
{"name": "name1", "age": 23},
{"name": "name2", "age": 25},
]
},
readonly=True,
)
@view_config(renderer="templates/form.pt", name="sequence_of_sequences")
@demonstrate("Sequence of Sequence Widgets")
def sequence_of_sequences(self):
class NameAndTitle(colander.Schema):
name = colander.SchemaNode(colander.String())
title = colander.SchemaNode(colander.String())
class NamesAndTitles(colander.SequenceSchema):
name_and_title = NameAndTitle(title="Name and Title")
class NamesAndTitlesSequences(colander.SequenceSchema):
names_and_titles = NamesAndTitles(title="Names and Titles")
class Schema(colander.Schema):
names_and_titles_sequence = NamesAndTitlesSequences(
title="Sequence of Sequences of Names and Titles"
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
outer = form["names_and_titles_sequence"]
outer.widget = deform.widget.SequenceWidget(min_len=1)
outer["names_and_titles"].widget = deform.widget.SequenceWidget(
min_len=1
)
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="sequence_of_defaulted_selects"
)
@demonstrate("Sequence of Defaulted Selects")
def sequence_of_defaulted_selects(self):
# See https://github.com/Pylons/deform/pull/79
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Peppers(colander.SequenceSchema):
pepper = colander.SchemaNode(
colander.String(),
default="jalapeno", # <--- raison d'etre
validator=colander.OneOf([x[0] for x in choices]),
widget=deform.widget.SelectWidget(values=choices),
title="Pepper Chooser",
description="Select a Pepper",
)
class Schema(colander.Schema):
peppers = Peppers()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt",
name="sequence_of_defaulted_selects_with_initial_item",
)
@demonstrate("Sequence of Defaulted Selects (with Initial Item)")
def sequence_of_defaulted_selects_with_initial_item(self):
# See https://github.com/Pylons/deformdemo/pull/15
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Peppers(colander.SequenceSchema):
pepper = colander.SchemaNode(
colander.String(),
default="jalapeno",
validator=colander.OneOf([x[0] for x in choices]),
widget=deform.widget.SelectWidget(values=choices),
title="Pepper Chooser",
description="Select a Pepper",
)
class Schema(colander.Schema):
peppers = Peppers()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
# raison d'etre below (1-length sequence widget means initial item
# rendered)
form["peppers"].widget = deform.widget.SequenceWidget(min_len=1)
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="sequence_of_constrained_len"
)
@demonstrate("Sequence of Constrained Min and Max Lengths")
def sequence_of_constrained_len(self):
class Names(colander.SequenceSchema):
name = colander.SchemaNode(colander.String())
class Schema(colander.Schema):
names = Names(
validator=colander.Length(2, 4),
title="At Least 2 At Most 4 Names",
widget=deform.widget.SequenceWidget(min_len=2, max_len=4),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="sequence_orderable")
@demonstrate("Sequence (of Mappings) with Ordering Enabled")
def sequence_orderable(self):
class Person(colander.Schema):
name = colander.SchemaNode(colander.String())
age = colander.SchemaNode(
colander.Integer(), validator=colander.Range(0, 200)
)
class People(colander.SequenceSchema):
person = Person()
class Schema(colander.Schema):
people = People(
widget=deform.widget.SequenceWidget(orderable=True)
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="file")
@demonstrate("File Upload Widget")
def file(self):
class Schema(colander.Schema):
upload = colander.SchemaNode(
deform.FileData(),
widget=deform.widget.FileUploadWidget(tmpstore),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, success=tmpstore.clear)
@view_config(renderer="templates/form.pt", name="file_readonly")
@demonstrate("File Upload Widget (read-only)")
def file_readonly(self):
class Schema(colander.Schema):
upload = colander.SchemaNode(
deform.FileData(),
widget=deform.widget.FileUploadWidget(tmpstore, readonly=True),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
appstruct = {"upload": {"uid": "123", "filename": "leavesofgrass.png"}}
return self.render_form(
form, appstruct=appstruct, success=tmpstore.clear
)
@view_config(renderer="templates/form.pt", name="dateparts")
@demonstrate("Date Parts Widget")
def dateparts(self):
import datetime
class Schema(colander.Schema):
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DatePartsWidget(),
validator=colander.Range(
min=datetime.date(2010, 1, 1),
min_err=_("${val} is earlier than earliest date ${min}"),
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="dateparts_readonly")
@demonstrate("Date Parts Widget (read-only)")
def dateparts_readonly(self):
import datetime
class Schema(colander.Schema):
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DatePartsWidget(readonly=True),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(
form, appstruct={"date": datetime.date(2010, 5, 5)}
)
@view_config(renderer="templates/form.pt", name="dateinput")
@demonstrate("Date Input Widget")
def dateinput(self):
import datetime
class Schema(colander.Schema):
somedate = colander.SchemaNode(
colander.Date(),
validator=colander.Range(
min=datetime.date(datetime.date.today().year, 1, 1),
min_err=_("${val} is earlier than earliest date ${min}"),
),
title="Date",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="timeinput")
@demonstrate("Time Input")
def timeinput(self):
import datetime
class Schema(colander.Schema):
sometime = colander.SchemaNode(
colander.Time(),
validator=colander.Range(
min=datetime.time(12, 16),
min_err=_("${val} is earlier than earliest time ${min}"),
),
title="Time",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="datetimeinput")
@demonstrate("DateTime Input Widget")
def datetimeinput(self):
import datetime
class Schema(colander.Schema):
date_time = colander.SchemaNode(
colander.DateTime(),
validator=colander.Range(
min=datetime.datetime(
datetime.date.today().year,
1,
1,
12,
30,
tzinfo=iso8601.UTC,
),
min_err=_(
"${val} is earlier than earliest datetime ${min}"
),
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="datetimeinput_readonly")
@demonstrate("DateTime Input Widget (read-only)")
def datetimeinput_readonly(self):
import datetime
then = datetime.datetime(2011, 5, 5, 1, 2)
class Schema(colander.Schema):
date_time = colander.SchemaNode(
colander.DateTime(),
widget=deform.widget.DateTimeInputWidget(readonly=True),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct={"date_time": then})
@view_config(renderer="templates/form.pt", name="edit")
@demonstrate("Edit Form")
def edit(self):
import datetime
class Mapping(colander.Schema):
name = colander.SchemaNode(
colander.String(), description="Content name"
)
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DatePartsWidget(),
description="Content date",
)
class Schema(colander.Schema):
number = colander.SchemaNode(colander.Integer())
mapping = Mapping()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
# We don't need to supply all the values required by the schema
# for an initial rendering, only the ones the app actually has
# values for. Notice below that we don't pass the ``name``
# value specified by the ``Mapping`` schema.
appstruct = {
"number": 42,
"mapping": {"date": datetime.date(2010, 4, 9)},
}
return self.render_form(form, appstruct=appstruct)
@view_config(renderer="templates/form.pt", name="interfield")
@demonstrate("Inter-Field Validation")
def interfield(self):
class Schema(colander.Schema):
name = colander.SchemaNode(
colander.String(), description="Content name"
)
title = colander.SchemaNode(
colander.String(),
description="Content title (must start with content name)",
)
def validator(form, value):
if not value["title"].startswith(value["name"]):
exc = colander.Invalid(form, "Title must start with name")
exc["title"] = "Must start with name %s" % value["name"]
raise exc
schema = Schema(validator=validator)
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="fielddefaults")
@demonstrate("Field Defaults")
def fielddefaults(self):
class Schema(colander.Schema):
artist = colander.SchemaNode(
colander.String(), default="Grandaddy", description="Song name"
)
album = colander.SchemaNode(
colander.String(), default="Just Like the Fambly Cat"
)
song = colander.SchemaNode(
colander.String(), description="Song name"
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="nonrequiredfields")
@demonstrate("Non-Required Fields")
def nonrequiredfields(self):
class Schema(colander.Schema):
required = colander.SchemaNode(
colander.String(), description="Required Field"
)
notrequired = colander.SchemaNode(
colander.String(),
missing=unicode(""),
description="Unrequired Field",
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="nonrequired_number_fields"
)
@demonstrate("Non-Required Number Fields")
def nonrequired_number_fields(self):
class Schema(colander.Schema):
required = colander.SchemaNode(
colander.Int(), description="Required Field"
)
notrequired = colander.SchemaNode(
colander.Float(), missing=0, description="Unrequired Field"
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="unicodeeverywhere")
@demonstrate("Unicode Everywhere")
def unicodeeverywhere(self):
class Schema(colander.Schema):
field = colander.SchemaNode(
colander.String(),
title=unicode("По оживлённым берегам", "utf-8"),
description=unicode(
"子曰:「學而時習之,不亦說乎?有朋自遠方來,不亦樂乎? " "人不知而不慍,不亦君子乎?」", "utf-8"
),
default=unicode("☃", "utf-8"),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select")
@demonstrate("Select Widget")
def select(self):
choices = (
("", "- Select -"),
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_with_size")
@demonstrate("Select Widget (with size)")
def select_with_size(self):
choices = (
("", "- Select -"),
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(values=choices, size=2),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_with_unicode")
@demonstrate("Select Widget (with unicode)")
def select_with_unicode(self):
choices = (
("", "- Select -"),
(unicode("ハバネロ", "utf-8"), "Habanero"),
(unicode("ハラペーニョ", "utf-8"), "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_with_default")
@demonstrate("Select Widget (with default)")
def select_with_default(self):
choices = (
("", "- Select -"),
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
default="jalapeno",
widget=deform.widget.SelectWidget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_with_multiple")
@demonstrate("Select Widget (with multiple)")
def select_with_multiple(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.SelectWidget(
values=choices, multiple=True
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt",
name="select_with_multiple_default_integers",
)
@demonstrate("Select Widget (with multiple default integers)")
def select_with_multiple_default_integers(self):
choices = ((1, "Habanero"), (2, "Jalapeno"), (3, "Chipotle"))
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
default=[1, 2],
widget=deform.widget.SelectWidget(
values=choices, multiple=True
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_with_deferred")
@demonstrate("Select Widget (with deferred choices and default)")
def select_with_deferred(self):
@colander.deferred
def deferred_choices_widget(node, kw):
choices = kw.get("choices")
return deform.widget.SelectWidget(values=choices)
@colander.deferred
def deferred_default(node, kw):
return kw["default"]
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
default=deferred_default,
widget=deferred_choices_widget,
)
choices = (
("", "- Select -"),
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
schema = Schema().bind(choices=choices, default="jalapeno")
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_integer")
@demonstrate("Select Widget (with Integer values)")
def select_integer(self):
choices = (("", "- Select -"), (0, "Zero"), (1, "One"), (2, "Two"))
class Schema(colander.Schema):
number = colander.SchemaNode(
colander.Integer(),
widget=deform.widget.SelectWidget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_with_optgroup")
@demonstrate("Select Widget (with optgroup)")
def select_with_optgroup(self):
from deform.widget import OptGroup
choices = (
("", "Select your favorite musician"),
OptGroup(
"Guitarists",
("page", "Jimmy Page"),
("hendrix", "Jimi Hendrix"),
),
OptGroup(
"Drummers",
("cobham", "Billy Cobham"),
("bonham", "John Bonham"),
),
)
class Schema(colander.Schema):
musician = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt",
name="select_with_optgroup_and_label_attributes",
)
@demonstrate("Select Widget (with optgroup and label attributes)")
def select_with_optgroup_and_label_attributes(self):
# One may or may not notice any difference with
# 'select_with_optgroup' above, depending on the browser being
# used. See widget's documentation for further details.
from deform.widget import OptGroup
choices = (
("", "Select your favorite musician"),
OptGroup(
"Guitarists",
("page", "Jimmy Page"),
("hendrix", "Jimi Hendrix"),
),
OptGroup(
"Drummers",
("cobham", "Billy Cobham"),
("bonham", "John Bonham"),
),
)
long_label_gener = lambda group, label: " - ".join( # noQA
(group, label)
)
class Schema(colander.Schema):
musician = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(
values=choices, long_label_generator=long_label_gener
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select_readonly")
@demonstrate("Select Widget (read-only)")
def select_readonly(self):
from deform.widget import OptGroup
choices = (
("", "Select your favorite musician"),
OptGroup(
"Guitarists",
("page", "Jimmy Page"),
("hendrix", "Jimi Hendrix"),
),
OptGroup(
"Drummers",
("cobham", "Billy Cobham"),
("bonham", "John Bonham"),
),
)
class Schema(colander.Schema):
musician = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(
values=choices, readonly=True
),
)
multiple_musicians = colander.SchemaNode(
colander.Set(),
widget=deform.widget.SelectWidget(
values=choices, multiple=True, readonly=True
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
appstruct = {
"musician": "cobham",
"multiple_musicians": ["cobham", "page"],
}
return self.render_form(form, appstruct=appstruct)
@view_config(renderer="templates/form.pt", name="select2")
@demonstrate("Select2 Widget")
def select2(self):
choices = (
("", "- Select -"),
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.Select2Widget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select2_with_multiple")
@demonstrate("Select2 Widget (with multiple)")
def select2_with_multiple(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.Select2Widget(
values=choices, multiple=True
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select2_with_optgroup")
@demonstrate("Select2 Widget (with optgroup)")
def select2_with_optgroup(self):
from deform.widget import OptGroup
choices = (
("", "Select your favorite musician"),
OptGroup(
"Guitarists",
("page", "Jimmy Page"),
("hendrix", "Jimi Hendrix"),
),
OptGroup(
"Drummers",
("cobham", "Billy Cobham"),
("bonham", "John Bonham"),
),
)
class Schema(colander.Schema):
musician = colander.SchemaNode(
colander.String(),
widget=deform.widget.Select2Widget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="select2_with_tags")
@demonstrate("Select2 Widget (with tags)")
def select2_with_tags(self):
choices = ()
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.Select2Widget(values=choices, tags=True),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="select2_with_tags_and_multiple"
)
@demonstrate("Select2 Widget (with tags and multiple)")
def select2_with_tags_and_multiple(self):
choices = ()
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.Select2Widget(
values=choices, multiple=True, tags=True
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="selectize")
@demonstrate("Selectize Widget")
def selectize(self):
choices = (
("", "- Select -"),
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectizeWidget(values=choices),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="selectize_with_multiple")
@demonstrate("Selectize Widget (with multiple)")
def selectize_with_multiple(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.SelectizeWidget(
values=choices,
multiple=True,
attributes={
"placeholder": "Select...",
},
),
validator=colander.Length(
min=1, min_err="You must select at least one pepper."
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="selectize_with_optgroup")
@demonstrate("Selectize Widget (with optgroup)")
def selectize_with_optgroup(self):
from deform.widget import OptGroup
choices = (
("", "Select your favorite musician"),
OptGroup(
"Guitarists",
("page", "Jimmy Page"),
("hendrix", "Jimi Hendrix"),
),
OptGroup(
"Drummers",
("cobham", "Billy Cobham"),
("bonham", "John Bonham"),
),
)
class Schema(colander.Schema):
musician = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectizeWidget(
values=choices,
attributes={
"placeholder": "Select...",
},
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="selectize_with_tags")
@demonstrate("Selectize Widget (with tags)")
def selectize_with_tags(self):
choices = ()
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectizeWidget(
values=choices,
tags=True,
selectize_options={
"createOnBlur": True,
"create": True,
},
attributes={
"placeholder": "Add a tag...",
},
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="selectize_with_tags_and_multiple"
)
@demonstrate("Selectize Widget (with tags and multiple)")
def selectize_with_tags_and_multiple(self):
choices = ()
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.SelectizeWidget(
values=choices,
tags=True,
multiple=True,
selectize_options={
"createOnBlur": True,
"create": True,
},
attributes={
"placeholder": "Add a tag...",
},
),
validator=colander.Length(
min=1, min_err="You must enter at least one tag."
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkboxchoice")
@demonstrate("Checkbox Choice Widget")
def checkboxchoice(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.CheckboxChoiceWidget(values=choices),
validator=colander.Length(min=1),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkboxchoice_inline")
@demonstrate("Checkbox Choice Widget (inline)")
def checkboxchoice_inline(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.CheckboxChoiceWidget(
values=choices, inline=True
),
validator=colander.Length(min=1),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkboxchoice2")
@demonstrate("Checkbox Choice Widget (with required field)")
def checkboxchoice2(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
@colander.deferred
def deferred_checkbox_widget(node, kw):
return deform.widget.CheckboxChoiceWidget(values=choices)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(), widget=deferred_checkbox_widget
)
required = colander.SchemaNode(colander.String())
schema = Schema()
schema = schema.bind()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="checkboxchoice_readonly")
@demonstrate("Checkbox Choice Widget (read-only)")
def checkboxchoice_readonly(self):
choices = (
("habanero", "Habanero"),
("jalapeno", "Jalapeno"),
("chipotle", "Chipotle"),
)
class Schema(colander.Schema):
pepper = colander.SchemaNode(
colander.Set(),
widget=deform.widget.CheckboxChoiceWidget(
values=choices, readonly=True
),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(
form, appstruct={"pepper": ["chipotle", "jalapeno"]}
)
@view_config(renderer="templates/form.pt", name="i18n")
@demonstrate("Internationalization")
def i18n(self):
minmax = {"min": 1, "max": 10}
locale_name = get_locale_name(self.request)
class Schema(colander.Schema):
number = colander.SchemaNode(
colander.Integer(),
title=_("A number between ${min} and ${max}", mapping=minmax),
description=_(
"A number between ${min} and ${max}", mapping=minmax
),
validator=colander.Range(1, 10),
)
_LOCALE_ = colander.SchemaNode(
colander.String(),
widget=deform.widget.HiddenWidget(),
default=locale_name,
)
schema = Schema()
form = deform.Form(
schema, buttons=[deform.Button("submit", _("Submit"))]
)
return self.render_form(form, is_i18n=True)
@view_config(renderer="templates/form.pt", name="hidden_field")
@demonstrate("Hidden Widget")
def hidden_field(self):
class Schema(colander.Schema):
sneaky = colander.SchemaNode(
colander.Boolean(),
widget=deform.widget.HiddenWidget(),
default=True,
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="hiddenmissing")
@demonstrate("Hidden Widget (missing, representing an Integer)")
def hiddenmissing(self):
class Schema(colander.Schema):
title = colander.SchemaNode(colander.String())
number = colander.SchemaNode(
colander.Integer(),
widget=deform.widget.HiddenWidget(),
missing=colander.null,
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="text_input_masks")
@demonstrate("Text Input Masks")
def text_input_masks(self):
class Schema(colander.Schema):
ssn = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(mask="999-99-9999"),
)
date = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(mask="99/99/9999"),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="textareacsv")
@demonstrate("Text Area CSV Widget")
def textareacsv(self):
class Row(colander.TupleSchema):
first = colander.SchemaNode(colander.Integer())
second = colander.SchemaNode(colander.String())
third = colander.SchemaNode(colander.Decimal())
class Rows(colander.SequenceSchema):
row = Row()
class Schema(colander.Schema):
csv = Rows()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
form["csv"].widget = deform.widget.TextAreaCSVWidget(rows=10, cols=60)
appstruct = {"csv": [(1, "hello", 4.5), (2, "goodbye", 5.5)]}
return self.render_form(form, appstruct=appstruct)
@view_config(renderer="templates/form.pt", name="textinputcsv")
@demonstrate("Text Input CSV Widget")
def textinputcsv(self):
class Row(colander.TupleSchema):
first = colander.SchemaNode(colander.Integer())
second = colander.SchemaNode(colander.String())
third = colander.SchemaNode(colander.Decimal())
class Schema(colander.Schema):
csv = Row()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
# we don't need to assign a widget; the text input csv widget is the
# default widget for tuples
appstruct = {"csv": (1, "hello", 4.5)}
return self.render_form(form, appstruct=appstruct)
@view_config(renderer="templates/form.pt", name="require_one_or_another")
@demonstrate("Require One Field or Another")
def require_one_or_another(self):
class Schema(colander.Schema):
one = colander.SchemaNode(
colander.String(),
missing=unicode(""),
title="One (required if Two is not supplied)",
)
two = colander.SchemaNode(
colander.String(),
missing=unicode(""),
title="Two (required if One is not supplied)",
)
def validator(form, value):
if not value["one"] and not value["two"]:
exc = colander.Invalid(
form, 'A value for either "one" or "two" is required'
)
exc["one"] = "Required if two is not supplied"
exc["two"] = "Required if one is not supplied"
raise exc
schema = Schema(validator=validator)
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt",
name="multiple_error_messages_mapping",
)
@demonstrate("Multiple Error Messages For a Single Widget (Mapping)")
def multiple_error_messages_mapping(self):
def v1(node, value):
msg = _("Error ${num}", mapping=dict(num=1))
raise colander.Invalid(node, msg)
def v2(node, value):
msg = _("Error ${num}", mapping=dict(num=2))
raise colander.Invalid(node, msg)
def v3(node, value):
msg = _("Error ${num}", mapping=dict(num=3))
raise colander.Invalid(node, msg)
class Schema(colander.Schema):
field = colander.SchemaNode(
colander.String(),
title="Fill in a value and submit to see multiple errors",
validator=colander.All(v1, v2, v3),
)
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="multiple_error_messages_seq"
)
@demonstrate("Multiple Error Messages For a Single Widget (Sequence)")
def multiple_error_messages_seq(self):
def v1(node, value):
msg = _("Error ${num}", mapping=dict(num=1))
raise colander.Invalid(node, msg)
def v2(node, value):
msg = _("Error ${num}", mapping=dict(num=2))
raise colander.Invalid(node, msg)
def v3(node, value):
msg = _("Error ${num}", mapping=dict(num=3))
raise colander.Invalid(node, msg)
class Sequence(colander.SequenceSchema):
field = colander.SchemaNode(
colander.String(),
title="Fill in a value and submit to see multiple errors",
validator=colander.All(v1, v2, v3),
)
class Schema(colander.Schema):
fields = Sequence()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="multiple_forms")
@demonstrate("Multiple Forms on the Same Page")
def multiple_forms(self):
import itertools
# We need to make sure the form field identifiers for the two
# forms do not overlap so accessibility features continue to work,
# such as focusing the field related to a legend when the
# legend is clicked on.
# We do so by creating an ``itertools.count`` object and
# passing that object as the ``counter`` keyword argument to
# the constructor of both forms. As a result, the second
# form's element identifiers will not overlap the first
# form's.
counter = itertools.count()
class Schema1(colander.Schema):
name1 = colander.SchemaNode(colander.String())
schema1 = Schema1()
form1 = deform.Form(
schema1, buttons=("submit",), formid="form1", counter=counter
)
class Schema2(colander.Schema):
name2 = colander.SchemaNode(colander.String())
schema2 = Schema2()
form2 = deform.Form(
schema2, buttons=("submit",), formid="form2", counter=counter
)
html = []
captured = None
if "submit" in self.request.POST:
posted_formid = self.request.POST["__formid__"]
for (formid, form) in [("form1", form1), ("form2", form2)]:
if formid == posted_formid:
try:
controls = self.request.POST.items()
captured = form.validate(controls)
html.append(form.render(captured))
except deform.ValidationFailure as e:
# the submitted values could not be validated
html.append(e.render())
else:
html.append(form.render())
else:
for form in form1, form2:
html.append(form.render())
html = "".join(html)
code, start, end = self.get_code(1)
# values passed to template for rendering
return {
"form": html,
"captured": repr(captured),
"code": code,
"start": start,
"demos": self.get_demos(),
"end": end,
"title": "Multiple Forms on the Same Page",
}
@view_config(renderer="templates/form.pt", name="widget_adapter")
@demonstrate("Widget Adapter")
def widget_adapter(self):
# Formish allows you to pair a widget against a type that
# doesn't "natively" lend itself to being representable by the
# widget. For example, it allows you to use a textarea widget
# against a sequence type. To provide this feature, Formish
# uses an adapter to convert the sequence data to text during
# serialization and from text back to a sequence during
# deserialization.
#
# Deform doesn't have such a feature out of the box. This is
# on purpose: the feature is really too complicated and
# magical for civilians. However, if you really want or need
# it, you can add yourself as necessary using an adapter
# pattern.
#
# In the demo method below, we adapt a "normal" textarea
# widget for use against a sequence. The resulting browser UI
# is the same as if we had used a TextAreaCSVWidget against
# the sequence as in the "textareacsv" test method.
#
# N.B.: we haven't automated the lookup of the widget adapter
# based on the type of the field and the type of the widget.
# Instead, we just construct an adapter manually. Adding an
# abstraction to the lookup based on the widget and schema
# types being adapted is easy enough, but trying to follow the
# code path of the abstraction becomes brain bending.
# Therefore, we don't bother to show it.
class Row(colander.TupleSchema):
first = colander.SchemaNode(colander.Integer())
second = colander.SchemaNode(colander.String())
third = colander.SchemaNode(colander.Decimal())
class Rows(colander.SequenceSchema):
row = Row()
class Schema(colander.Schema):
csv = Rows()
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
inner_widget = deform.widget.TextAreaWidget(rows=10, cols=60)
widget = SequenceToTextWidgetAdapter(inner_widget)
form["csv"].widget = widget
appstruct = {"csv": [(1, "hello", 4.5), (2, "goodbye", 5.5)]}
return self.render_form(form, appstruct=appstruct)
@view_config(renderer="templates/form.pt", name="deferred_schema_bindings")
@demonstrate("Deferred Schema Bindings")
def deferred_schema_bindings(self):
import datetime
import colander
@colander.deferred
def deferred_date_validator(node, kw):
max_date = kw.get("max_date")
if max_date is None:
max_date = datetime.date.today()
return colander.Range(min=datetime.date.min, max=max_date)
@colander.deferred
def deferred_date_description(node, kw):
max_date = kw.get("max_date")
if max_date is None:
max_date = datetime.date.today()
return "Blog post date (no earlier than %s)" % max_date.ctime()
@colander.deferred
def deferred_date_missing(node, kw):
default_date = kw.get("default_date")
if default_date is None:
default_date = datetime.date.today()
return default_date
@colander.deferred
def deferred_body_validator(node, kw):
max_bodylen = kw.get("max_bodylen")
if max_bodylen is None:
max_bodylen = 1 << 18
return colander.Length(max=max_bodylen)
@colander.deferred
def deferred_body_description(node, kw):
max_bodylen = kw.get("max_bodylen")
if max_bodylen is None:
max_bodylen = 1 << 18
return "Blog post body (no longer than %s bytes)" % max_bodylen
@colander.deferred
def deferred_body_widget(node, kw):
body_type = kw.get("body_type")
if body_type == "richtext":
widget = deform.widget.RichTextWidget()
else:
widget = deform.widget.TextAreaWidget()
return widget
@colander.deferred
def deferred_category_validator(node, kw):
categories = kw.get("categories", [])
return colander.OneOf([x[0] for x in categories])
@colander.deferred
def deferred_category_widget(node, kw):
categories = kw.get("categories", [])
return deform.widget.RadioChoiceWidget(values=categories)
class BlogPostSchema(colander.Schema):
title = colander.SchemaNode(
colander.String(),
title="Title",
description="Blog post title",
validator=colander.Length(min=5, max=100),
widget=deform.widget.TextInputWidget(),
)
date = colander.SchemaNode(
colander.Date(),
title="Date",
missing=deferred_date_missing,
description=deferred_date_description,
validator=deferred_date_validator,
widget=deform.widget.DateInputWidget(),
)
body = colander.SchemaNode(
colander.String(),
title="Body",
description=deferred_body_description,
validator=deferred_body_validator,
widget=deferred_body_widget,
)
category = colander.SchemaNode(
colander.String(),
title="Category",
description="Blog post category",
validator=deferred_category_validator,
widget=deferred_category_widget,
)
schema = BlogPostSchema().bind(
max_date=datetime.date.max,
max_bodylen=5000,
body_type="richtext",
default_date=datetime.date.today(),
categories=[("one", "One"), ("two", "Two")],
)
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(renderer="templates/form.pt", name="pyramid_csrf_demo")
@demonstrate("Pyramid CSRF Demo (using schema binding)")
def pyramid_csrf_demo(self):
@colander.deferred
def deferred_csrf_default(node, kw):
request = kw.get("request")
csrf_token = request.session.get_csrf_token()
return csrf_token
@colander.deferred
def deferred_csrf_validator(node, kw):
def validate_csrf(node, value):
request = kw.get("request")
csrf_token = request.session.get_csrf_token()
if value != csrf_token:
raise ValueError("Bad CSRF token")
return validate_csrf
class CSRFSchema(colander.Schema):
csrf = colander.SchemaNode(
colander.String(),
default=deferred_csrf_default,
validator=deferred_csrf_validator,
widget=deform.widget.HiddenWidget(),
)
# subclass from CSRFSchema everywhere to get CSRF validation
class MySchema(CSRFSchema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=deform.widget.TextInputWidget(),
description="Enter some text",
)
schema = MySchema().bind(request=self.request)
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt",
name="sequence_with_prototype_that_has_no_name",
)
@demonstrate("Sequence With Prototype that Has No Name")
def sequence_with_prototype_that_has_no_name(self):
class EmailMessage(colander.Schema):
subject = colander.SchemaNode(colander.String())
to = colander.SchemaNode(
colander.Sequence(),
colander.SchemaNode(colander.String(), name="foo"),
)
schema = EmailMessage()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)
@view_config(
renderer="templates/form.pt", name="readonly_value_nonvalidation"
)
@demonstrate("Don't Validate Readonly Fields")
def readonly_value_nonvalidation(self):
@colander.deferred
def deferred_missing(node, kw):
return appstruct["readonly"]
class Values(colander.Schema):
readonly = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(readonly=True),
missing=deferred_missing,
)
readwrite = colander.SchemaNode(colander.String())
appstruct = {
"readonly": "Read Only",
"readwrite": "Read and Write",
}
schema = Values().bind()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct=appstruct)
@view_config(renderer="templates/form.pt", name="readonly_argument")
@demonstrate("Readonly Widget Argument")
def readonly_argument(self):
import datetime
class Schema(colander.Schema):
textinput = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(readonly=True),
missing=colander.null,
description="Text in a text input",
)
textarea = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextAreaWidget(readonly=True),
missing=colander.null,
description="Text in a textarea",
)
single_select = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(
values=[("a", "The letter a"), ("b", "The letter b")],
readonly=True,
),
missing=colander.null,
description="A letter",
)
multi_select = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(
values=[("a", "The letter a"), ("b", "The letter b")],
multiple=True,
readonly=True,
),
missing=colander.null,
description="Some letters",
)
richtext = colander.SchemaNode(
colander.String(),
widget=deform.widget.RichTextWidget(readonly=True),
description="Some text",
missing=colander.null,
)
money = colander.SchemaNode(
colander.Decimal(),
widget=deform.widget.MoneyInputWidget(readonly=True),
description="Some money",
missing=colander.null,
)
date = colander.SchemaNode(
colander.Date(),
widget=deform.widget.DateInputWidget(readonly=True),
description="Some date",
missing=colander.null,
)
appstruct = {
"textinput": "readonly text input",
"textarea": "readonly text area",
"single_select": "a",
"multi_select": ("a", "b"),
"richtext": "<p>Yo!</p>",
"money": decimal.Decimal(1),
"date": datetime.date(2010, 5, 5),
}
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct=appstruct)
@view_config(renderer="templates/form.pt", name="readonly_html")
@demonstrate("Readonly HTML Attribute")
def readonly_html(self):
"""
This form shows the widgets that support the HTML attribute
``readonly``.
"""
values = [
("a", "The letter a"),
("b", "The letter b"),
("c", "The letter c"),
]
class Schema(colander.Schema):
checkbox = colander.SchemaNode(
colander.Set(),
widget=deform.widget.CheckboxChoiceWidget(
values=values,
attributes={"onclick": "return false;"},
),
description="Readonly checkbox choices",
)
money = colander.SchemaNode(
colander.Decimal(),
widget=deform.widget.MoneyInputWidget(
attributes={"readonly": "readonly"}
),
description="Readonly money",
)
radio = colander.SchemaNode(
colander.String(),
widget=deform.widget.RadioChoiceWidget(
values=values,
attributes={"readonly": "readonly"},
),
description="Readonly radio choices",
)
select_single = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectWidget(
values=values,
attributes={"readonly": "readonly"},
),
description="Readonly select single",
)
selectize_multi = colander.SchemaNode(
colander.Set(),
widget=deform.widget.SelectizeWidget(
values=values,
multiple=True,
attributes={"readonly": "readonly"},
selectize_options={
"persist": False,
"plugins": ["remove_button"],
},
),
description="Readonly selectize multiple",
)
selectize_single = colander.SchemaNode(
colander.String(),
widget=deform.widget.SelectizeWidget(
values=values,
attributes={"readonly": "readonly"},
selectize_options={
"persist": False,
},
),
description="Readonly selectize single",
)
textarea = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextAreaWidget(
attributes={"readonly": "readonly"}
),
description="Readonly textarea",
)
textinput = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(
attributes={"readonly": "readonly"}
),
description="Readonly text input",
)
appstruct = {
"checkbox": "b",
"money": decimal.Decimal(1),
"radio": "b",
"select_single": "b",
"selectize_single": "b",
"selectize_multi": ("a", "b"),
"textarea": "readonly text area",
"textinput": "readonly text input",
}
schema = Schema()
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form, appstruct=appstruct)
@view_config(
renderer="templates/form.pt",
name="custom_classes_on_outermost_html_element",
)
@demonstrate("Custom classes on outermost html element of Widgets")
def custom_classes_on_outermost_html_element(self):
import datetime
class Mapping(colander.Schema):
upload = colander.SchemaNode(
deform.FileData(),
widget=deform.widget.FileUploadWidget(
tmpstore, item_css_class="mapped_widget_custom_class"
),
)
class Schema(colander.Schema):
text = colander.SchemaNode(
colander.String(),
widget=deform.widget.TextInputWidget(
item_css_class="top_level_mapping_widget_custom_class"
),
)
sequence = colander.SchemaNode(
colander.Sequence(),
colander.SchemaNode(
colander.Date(),
name="Sequence Item",
widget=deform.widget.DatePartsWidget(
item_css_class="sequenced_widget_custom_class"
),
),
default=[datetime.date.today()],
description="SequenceWidget",
)
mapping = Mapping(description="MappingWidget")
return self.render_form(deform.Form(Schema(), buttons=("submit",)))
class MemoryTmpStore(dict):
"""Instances of this class implement the
:class:`deform.interfaces.FileUploadTempStore` interface"""
def preview_url(self, uid):
return None
tmpstore = MemoryTmpStore()
class SequenceToTextWidgetAdapter(object):
def __init__(self, widget):
self.widget = widget
def __getattr__(self, name):
return getattr(self.widget, name)
def serialize(self, field, cstruct, readonly=False):
if cstruct is colander.null:
cstruct = []
textrows = getattr(field, "unparseable", None)
if textrows is None:
outfile = StringIO()
writer = csv.writer(outfile)
writer.writerows(cstruct)
textrows = outfile.getvalue()
return self.widget.serialize(
field, cstruct=textrows, readonly=readonly
)
def deserialize(self, field, pstruct):
text = self.widget.deserialize(field, pstruct)
if text is colander.null:
return text
if not text.strip():
return colander.null
try:
infile = StringIO(text)
reader = csv.reader(infile)
rows = list(reader)
except Exception as e:
field.unparseable = pstruct
raise colander.Invalid(field.schema, str(e))
return rows
def handle_error(self, field, error):
msgs = []
if error.msg:
field.error = error
else:
for e in error.children:
msgs.append("line %s: %s" % (e.pos + 1, e))
field.error = colander.Invalid(field.schema, "\n".join(msgs))
def main(global_config, **settings):
# paster serve entry point
settings["debug_templates"] = "true"
session_factory = SignedCookieSessionFactory("seekrit!")
config = Configurator(settings=settings, session_factory=session_factory)
config.add_translation_dirs(
"colander:locale", "deform:locale", "deformdemo:locale"
)
config.include("pyramid_chameleon")
# Set up Chameleon templates (ZTP) rendering paths
def translator(term):
# i18n localizing function
return get_localizer(get_current_request()).translate(term)
# Configure renderer
configure_zpt_renderer(
(
"deformdemo:custom_widgets",
"unofficial-deformdemo:custom_widgets",
),
translator,
)
config.add_static_view("static_deform", "deform:static")
config.add_route(
"unofficial-deformdemo", "/unofficial-deformdemo*traverse"
)
config.add_route("deformdemo", "*traverse")
def onerror(*arg):
pass
config.scan("deformdemo", onerror=onerror)
config.include("..unofficial-deformdemo")
return config.make_wsgi_app()
|