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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2016 Étienne Loks <etienne.loks_AT_peacefrogsDOTnet>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# See the file COPYING for details.
from collections import OrderedDict
import datetime
import os
import pyqrcode
import re
import requests
import shutil
import tempfile
from urllib.parse import urlparse, quote
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core import validators
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist
from django.core.files import File
from django.core.validators import MaxValueValidator, MinValueValidator
from django.forms.formsets import formset_factory
from django.forms.models import BaseModelFormSet, BaseFormSet
from django.shortcuts import reverse
from django.utils.text import slugify
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _, pgettext
from . import models
from . import widgets
from bootstrap_datepicker.widgets import DatePicker
from ishtar_common.templatetags.link_to_window import simple_link_to_window
from .forms import FinalForm, FormSet, reverse_lazy, name_validator, \
TableSelect, ManageOldType, CustomForm, FieldType, FormHeader, \
FormSetWithDeleteSwitches, BSForm, get_data_from_formset, \
file_size_validator, HistorySelect, CustomFormSearch, QAForm, IshtarForm, \
MultiSearchForm, LockForm
from ishtar_common.data_importer import ImporterError
from ishtar_common.utils import is_downloadable, clean_session_cache, \
max_size_help
from archaeological_operations.models import Operation
from archaeological_context_records.models import ContextRecord
from archaeological_finds.models import Find, FindBasket
from archaeological_warehouse.models import Container
def get_town_field(label=_("Town"), required=True):
help_text = _(
"<p>Type name, department code of the "
"town you would like to select. The search is insensitive to case."
"</p>\n<p>Only the first twenty results are displayed but specifying "
"the department code is generally sufficient to get the appropriate "
"result.</p>\n<p class='example'>For instance type \"saint denis 93\""
" for getting the french town Saint-Denis in the Seine-Saint-Denis "
"department.</p>")
# !FIXME hard_link, reverse_lazy doen't seem to work with formsets
return forms.IntegerField(
widget=widgets.JQueryAutoComplete(
"/" + settings.URL_PATH + 'autocomplete-town',
associated_model=models.Town),
validators=[models.valid_id(models.Town)], label=label,
help_text=mark_safe(help_text), required=required)
def get_advanced_town_field(label=_("Town"), required=True):
# !FIXME hard_link, reverse_lazy doen't seem to work with formsets
return forms.IntegerField(
widget=widgets.JQueryTown(
"/" + settings.URL_PATH + 'autocomplete-advanced-town'),
validators=[models.valid_id(models.Town)], label=label,
required=required)
def get_person_field(label=_("Person"), required=True, person_types=[]):
# !FIXME hard_link, reverse_lazy doen't seem to work with formsets
widget = None
url = "/" + settings.URL_PATH + 'autocomplete-person'
if person_types:
person_types = [
str(models.PersonType.objects.get(txt_idx=person_type).pk)
for person_type in person_types]
url += "/" + '_'.join(person_types)
widget = widgets.JQueryAutoComplete(url, associated_model=models.Person)
return forms.IntegerField(widget=widget, label=label, required=required,
validators=[models.valid_id(models.Person)])
class NewItemForm(forms.Form):
def __init__(self, *args, **kwargs):
self.limits = {}
if 'limits' in kwargs:
limits = kwargs.pop('limits')
if limits:
for item in limits.split(';'):
key, values = item.split('__')
self.limits[key] = values.split('-')
super(NewItemForm, self).__init__(*args, **kwargs)
def limit_fields(self):
for key in self.limits:
if key in self.fields and hasattr(self.fields[key], 'choices'):
new_choices = [
(value, lbl)
for value, lbl in self.fields[key].choices
if str(value) in self.limits[key]
]
self.fields[key].choices = new_choices
if len(new_choices) == 1:
self.fields[key].initial = [new_choices[0][0]]
class NewImportForm(BSForm, forms.ModelForm):
error_css_class = 'error'
required_css_class = 'required'
imported_images_link = forms.URLField(
label=_("Associated images (web link to a zip file)"),
required=False
)
class Meta:
model = models.Import
fields = (
'name', 'importer_type', 'imported_file', 'encoding',
'csv_sep', 'imported_images', 'imported_images_link',
'associated_group', 'conservative_import', 'skip_lines'
)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(NewImportForm, self).__init__(*args, **kwargs)
groups = models.TargetKeyGroup.objects.filter(available=True)
if not user.is_superuser:
groups = groups.filter(all_user_can_use=True)
if not groups.count():
self.fields.pop('associated_group')
else:
self.fields['associated_group'].choices = [(None, '--')] + \
[(g.pk, str(g)) for g in groups.all()]
self.fields['importer_type'].choices = [('', '--')] + [
(imp.pk, imp.name) for imp in models.ImporterType.objects.filter(
available=True
)
]
self.fields['imported_file'].validators = [file_size_validator]
self.fields['imported_images'].validators = [file_size_validator]
self._post_init()
def clean(self):
data = self.cleaned_data
if data.get('conservative_import', None) \
and data.get('importer_type') \
and not data.get('importer_type').unicity_keys:
raise forms.ValidationError(
_("This import type have no unicity type defined. "
"Conservative import is not possible."))
if data.get('imported_images_link', None) \
and data.get('imported_images', None):
raise forms.ValidationError(
_("You put either a file or a download link for images "
"but not both."))
return data
def clean_imported_images_link(self):
value = self.cleaned_data.get('imported_images_link', None)
if value:
try:
assert is_downloadable(value)
except (AssertionError, requests.exceptions.RequestException):
raise forms.ValidationError(
_("Invalid link or no file is available for this link."))
return value
def save(self, user, commit=True):
self.instance.user = user
imported_images_link = self.cleaned_data.pop('imported_images_link') \
if 'imported_images_link' in self.cleaned_data else None
item = super(NewImportForm, self).save(commit)
if not imported_images_link:
return item
request = requests.get(imported_images_link, stream=True)
ntf = tempfile.NamedTemporaryFile()
for block in request.iter_content(1024 * 8):
if not block:
break
ntf.write(block)
file_name = imported_images_link.split('/')[-1]
item.imported_images.save(file_name, File(ntf))
return item
class TargetKeyForm(forms.ModelForm):
class Meta:
model = models.TargetKey
fields = ('target', 'key', 'value')
widgets = {
'key': forms.TextInput(attrs={'readonly': 'readonly'}),
}
target = widgets.SelectReadonlyField(
model=models.ImportTarget, label=_("Target"))
value = widgets.Select2SimpleField(
label=_("Value"), required=False
)
remember = forms.ChoiceField(label=_("Remember"), choices=[],
required=False)
NULL_VALUE = '<NONE>'
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(TargetKeyForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
self.associated_import = None
if instance and instance.pk:
model = instance.target.associated_model
if model and \
self.user.has_perm('{}.change_{}'.format(
model._meta.app_label, model._meta.model_name)) and \
hasattr(model, 'admin_url'):
self.admin_url = instance.target.associated_model.admin_url()
self.associated_import = instance.associated_import
self.fields['target'].choices = [(instance.target.pk,
instance.target.verbose_name)]
self.fields['key'].widget.attrs['readonly'] = True
self.fields['key'].widget.attrs['title'] = str(instance)
self.fields['value'].choices = list(
instance.target.get_choices())
self.fields['value'].choices.insert(
1, (self.NULL_VALUE, _("Set to NULL")))
self.fields['key'].required = False
self.fields['target'].required = False
self.fields['value'].required = False
choices = [
('import', _("this import only")),
('me', _("me")),
]
if self.associated_import and self.associated_import.associated_group \
and (self.associated_import.associated_group.all_user_can_modify
or self.user.is_superuser):
choices += [
('group', str(_("the current group: {}")).format(
self.associated_import.associated_group))]
if self.user.is_superuser:
choices += [('all', _("all users"))]
self.fields['remember'].choices = choices
self.fields['remember'].widget.attrs['class'] = 'auto'
self.remember_choices = choices
def clean_target(self):
instance = getattr(self, 'instance', None)
if instance and instance.pk:
return instance.target
else:
return self.cleaned_data['target']
def clean_key(self):
instance = getattr(self, 'instance', None)
if instance and instance.pk:
return instance.key
else:
return self.cleaned_data['key']
def save(self, commit=True):
try:
super(TargetKeyForm, self).save(commit)
except ImporterError:
return
if not self.cleaned_data.get('value') or not self.user:
return
if self.cleaned_data['value'] == self.NULL_VALUE:
self.instance.value = None
self.instance.is_set = True
can_edit_group = \
self.associated_import and \
self.associated_import.associated_group and \
(self.associated_import.associated_group.all_user_can_modify
or self.user.is_superuser)
remember = self.cleaned_data.get('remember')
if remember == 'import' and self.associated_import:
self.instance.associated_import = self.associated_import
self.instance.associated_user = None
self.instance.associated_group = None
elif remember == 'group' and can_edit_group:
self.instance.associated_import = None
self.instance.associated_user = None
self.instance.associated_group = \
self.associated_import.associated_group
elif remember == 'all' and self.user.is_superuser:
self.instance.associated_import = None
self.instance.associated_user = None
self.instance.associated_group = None
else:
# for me!
self.instance.associated_import = None
self.instance.associated_user = self.user.ishtaruser
self.instance.associated_group = None
self.instance.save()
class TargetKeyFormset(BaseModelFormSet):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(TargetKeyFormset, self).__init__(*args, **kwargs)
def get_form_kwargs(self, index):
kwargs = super(TargetKeyFormset, self).get_form_kwargs(index)
kwargs['user'] = self.user
return kwargs
class OrganizationForm(ManageOldType, NewItemForm):
prefix = 'organization'
form_label = _("Organization")
associated_models = {'organization_type': models.OrganizationType,
"precise_town": models.Town}
name = forms.CharField(
label=_("Name"), max_length=300, validators=[name_validator])
organization_type = forms.ChoiceField(label=_("Organization type"),
choices=[])
url = forms.URLField(label=_("Web address"), required=False)
grammatical_gender = forms.ChoiceField(
label=_("Grammatical gender"),
choices=[('', '--')] + list(models.GENDER),
required=False, help_text=_("Can be used by templates"))
address = forms.CharField(label=_("Address"), widget=forms.Textarea,
required=False)
address_complement = forms.CharField(label=_("Address complement"),
widget=forms.Textarea, required=False)
postal_code = forms.CharField(label=_("Postal code"), max_length=10,
required=False)
town = forms.CharField(label=_("Town (freeform)"), max_length=30,
required=False)
precise_town = get_town_field(required=False)
country = forms.CharField(label=_("Country"), max_length=30,
required=False)
email = forms.EmailField(label=_("Email"), required=False)
phone = forms.CharField(label=_("Phone"), max_length=18, required=False)
mobile_phone = forms.CharField(label=_("Mobile phone"), max_length=18,
required=False)
def __init__(self, *args, **kwargs):
super(OrganizationForm, self).__init__(*args, **kwargs)
self.fields['organization_type'].choices = \
models.OrganizationType.get_types(
initial=self.init_data.get('organization_type'))
self.fields['organization_type'].help_text = \
models.OrganizationType.get_help()
self.limit_fields()
def save(self, user, item=None):
dct = self.cleaned_data
dct['history_modifier'] = user
dct['organization_type'] = models.OrganizationType.objects.get(
pk=dct['organization_type'])
if dct["precise_town"]:
try:
dct["precise_town"] = models.Town.objects.get(
pk=dct["precise_town"])
except models.Town.DoesNotExist:
dct.pop("precise_town")
if not item:
new_item = models.Organization(**dct)
else:
new_item = item
for k in dct:
setattr(new_item, k, dct[k])
new_item.save()
return new_item
class OrganizationSelect(CustomForm, TableSelect):
_model = models.Organization
search_vector = forms.CharField(
label=_("Full text search"), widget=widgets.SearchWidget(
'ishtar-common', 'organization'
))
name = forms.CharField(label=_("Name"), max_length=300)
organization_type = forms.ChoiceField(label=_("Type"), choices=[])
def __init__(self, *args, **kwargs):
super(OrganizationSelect, self).__init__(*args, **kwargs)
self.fields['organization_type'].choices = \
models.OrganizationType.get_types()
class OrganizationFormSelection(CustomFormSearch):
SEARCH_AND_SELECT = True
form_label = _("Organization search")
associated_models = {'pk': models.Organization}
currents = {'pk': models.Organization}
pk = forms.IntegerField(
label="",
widget=widgets.DataTable(
reverse_lazy('get-organization'), OrganizationSelect,
models.Organization,
source_full=reverse_lazy('get-organization-full')),
validators=[models.valid_id(models.Organization)])
class OrganizationFormMultiSelection(MultiSearchForm):
form_label = _("Organization search")
associated_models = {'pks': models.Organization}
pk = forms.CharField(
label="",
required=True,
widget=widgets.DataTable(
reverse_lazy('get-organization'), OrganizationSelect,
models.Organization,
multiple_select=True,
source_full=reverse_lazy('get-organization-full')),
validators=[models.valid_ids(models.Organization)])
class QAOrganizationFormMulti(QAForm):
form_admin_name = _("Organization - Quick action - Modify")
form_slug = "organization-quickaction-modify"
base_models = ['qa_organization_type']
associated_models = {
'qa_organization_type': models.OrganizationType,
}
MULTI = True
REPLACE_FIELDS = [
'qa_organization_type',
]
qa_organization_type = forms.ChoiceField(
label=_("Organization type"), required=False
)
TYPES = [
FieldType('qa_organization_type', models.OrganizationType),
]
class ManualMerge(object):
def clean_to_merge(self):
value = self.cleaned_data.get('to_merge', None) or []
if value:
value = value.split(',')
values = []
for val in value:
try:
values.append(int(val))
except ValueError:
pass
if len(values) < 2:
raise forms.ValidationError(_("At least two items have to be "
"selected."))
self.cleaned_data['to_merge'] = values
return values
def get_items(self):
items = []
model = self.associated_models['to_merge']
for pk in sorted(self.cleaned_data['to_merge']):
try:
items.append(model.objects.get(pk=pk))
except model.DoesNotExist:
pass
return items
class MergeIntoForm(forms.Form):
main_item = forms.ChoiceField(
label=_("Merge all items into"), choices=[],
widget=forms.RadioSelect())
def __init__(self, *args, **kwargs):
self.items = kwargs.pop('items')
super(MergeIntoForm, self).__init__(*args, **kwargs)
self.fields['main_item'].choices = []
for pk in self.items:
try:
item = self.associated_model.objects.get(pk=pk)
except self.associated_model.DoesNotExist:
continue
self.fields['main_item'].choices.append(
(item.pk, mark_safe("{} {}".format(simple_link_to_window(item),
str(item)))))
def merge(self):
model = self.associated_model
try:
main_item = model.objects.get(pk=self.cleaned_data['main_item'])
except model.DoesNotExist:
return
for pk in self.items:
if pk == str(main_item.pk):
continue
try:
item = model.objects.get(pk=pk)
except model.DoesNotExist:
continue
main_item.merge(item)
return main_item
class OrgaMergeFormSelection(ManualMerge, forms.Form):
SEARCH_AND_SELECT = True
form_label = _("Organization to merge")
associated_models = {'to_merge': models.Organization}
currents = {'to_merge': models.Organization}
to_merge = forms.CharField(
label="", required=False,
widget=widgets.DataTable(
reverse_lazy('get-organization'), OrganizationSelect,
models.Organization,
multiple_select=True,
source_full=reverse_lazy('get-organization-full')),)
class OrgaMergeIntoForm(MergeIntoForm):
associated_model = models.Organization
class BaseOrganizationForm(forms.ModelForm):
form_prefix = "orga"
class Meta:
model = models.Organization
fields = ['name', 'organization_type',
'grammatical_gender', 'address', 'address_complement',
'town', 'postal_code']
class PersonSelect(CustomForm, TableSelect):
_model = models.Person
search_vector = forms.CharField(
label=_("Full text search"), widget=widgets.SearchWidget(
'ishtar-common', 'person'
))
name = forms.CharField(label=_("Name"), max_length=200)
surname = forms.CharField(label=_("Surname"), max_length=50)
email = forms.CharField(label=_("Email"), max_length=75)
person_types = forms.ChoiceField(label=_("Type"), choices=[])
attached_to = forms.IntegerField(
label=_("Organization"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-organization'),
associated_model=models.Organization),
validators=[models.valid_id(models.Organization)])
def __init__(self, *args, **kwargs):
super(PersonSelect, self).__init__(*args, **kwargs)
self.fields['person_types'].choices = models.PersonType.get_types()
class PersonFormSelection(CustomFormSearch):
SEARCH_AND_SELECT = True
form_label = _("Person search")
associated_models = {'pk': models.Person}
currents = {'pk': models.Person}
pk = forms.IntegerField(
label="",
widget=widgets.DataTable(
reverse_lazy('get-person'), PersonSelect, models.Person,
source_full=reverse_lazy('get-person-full')),
validators=[models.valid_id(models.Person)])
class PersonFormMultiSelection(MultiSearchForm):
form_label = _("Person search")
associated_models = {'pks': models.Person}
pk = forms.CharField(
label="",
required=True,
widget=widgets.DataTable(
reverse_lazy('get-person'), PersonSelect, models.Person,
multiple_select=True,
source_full=reverse_lazy('get-person-full')),
validators=[models.valid_ids(models.Person)])
class QAPersonFormMulti(QAForm):
form_admin_name = _("Person - Quick action - Modify")
form_slug = "person-quickaction-modify"
base_models = ['qa_title']
associated_models = {
'qa_title': models.TitleType,
'qa_attached_to': models.Organization,
}
MULTI = True
REPLACE_FIELDS = [
'qa_title',
'qa_attached_to'
]
qa_title = forms.ChoiceField(
label=_("Title"), required=False
)
qa_attached_to = forms.IntegerField(
label=_("Organization"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-organization'),
associated_model=models.Organization),
validators=[models.valid_id(models.Organization)],
required=False
)
TYPES = [
FieldType('qa_title', models.TitleType),
]
def _get_qa_attached_to(self, value):
try:
value = models.Organization.objects.get(pk=value).cached_label
except models.Organization.DoesNotExist:
return ""
return value
class PersonMergeFormSelection(ManualMerge, forms.Form):
SEARCH_AND_SELECT = True
form_label = _("Person to merge")
associated_models = {'to_merge': models.Person}
currents = {'to_merge': models.Person}
to_merge = forms.CharField(
label="", required=False,
widget=widgets.DataTable(
reverse_lazy('get-person'),
PersonSelect, models.Person,
multiple_select=True,
source_full=reverse_lazy('get-person-full')),)
class PersonMergeIntoForm(MergeIntoForm):
associated_model = models.Person
class SimplePersonForm(ManageOldType, NewItemForm):
extra_form_modals = ["organization"]
form_label = _("Identity")
associated_models = {'attached_to': models.Organization,
'title': models.TitleType,
"precise_town": models.Town}
title = forms.ChoiceField(label=_("Title"), choices=[], required=False)
salutation = forms.CharField(label=_("Salutation"), max_length=200,
required=False)
surname = forms.CharField(label=_("Surname"), max_length=50,
validators=[name_validator])
name = forms.CharField(label=_("Name"), max_length=200,
validators=[name_validator])
raw_name = forms.CharField(label=_("Raw name"), max_length=300,
required=False)
email = forms.EmailField(label=_("Email"), required=False)
phone_desc = forms.CharField(label=_("Phone description"), max_length=300,
required=False)
phone = forms.CharField(label=_("Phone"), max_length=18, required=False)
phone_desc2 = forms.CharField(label=_("Phone description 2"),
max_length=300, required=False)
phone2 = forms.CharField(label=_("Phone 2"), max_length=18,
required=False)
phone_desc3 = forms.CharField(label=_("Phone description 3"),
max_length=300, required=False)
phone3 = forms.CharField(label=_("Phone 3"), max_length=18,
required=False)
mobile_phone = forms.CharField(label=_("Mobile phone"), max_length=18,
required=False)
attached_to = forms.IntegerField(
label=_("Current organization"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-organization'),
associated_model=models.Organization, new=True),
validators=[models.valid_id(models.Organization)], required=False)
address = forms.CharField(label=_("Address"), widget=forms.Textarea,
required=False)
address_complement = forms.CharField(
label=_("Address complement"), widget=forms.Textarea, required=False)
postal_code = forms.CharField(label=_("Postal code"), max_length=10,
required=False)
town = forms.CharField(label=_("Town (freeform)"), max_length=30,
required=False)
precise_town = get_town_field(required=False)
country = forms.CharField(label=_("Country"), max_length=30,
required=False)
alt_address = forms.CharField(label=_("Other address: address"),
widget=forms.Textarea, required=False)
alt_address_complement = forms.CharField(
label=_("Other address: address complement"),
widget=forms.Textarea, required=False)
alt_postal_code = forms.CharField(label=_("Other address: postal code"),
max_length=10, required=False)
alt_town = forms.CharField(label=_("Other address: town"), max_length=30,
required=False)
alt_country = forms.CharField(label=_("Other address: country"),
max_length=30, required=False)
def __init__(self, *args, **kwargs):
super(SimplePersonForm, self).__init__(*args, **kwargs)
self.fields['raw_name'].widget.attrs['readonly'] = True
self.fields['title'].choices = models.TitleType.get_types(
initial=self.init_data.get('title'))
class PersonUserSelect(PersonSelect):
ishtaruser__isnull = forms.NullBooleanField(
label=_("Already has an account"))
class PersonUserFormSelection(PersonFormSelection):
SEARCH_AND_SELECT = True
form_label = _("Person search")
associated_models = {'pk': models.Person}
currents = {'pk': models.Person}
pk = forms.IntegerField(
label="",
widget=widgets.DataTable(reverse_lazy('get-person-for-account'),
PersonUserSelect, models.Person,
table_cols="TABLE_COLS_ACCOUNT"),
validators=[models.valid_id(models.Person)])
class IshtarUserSelect(TableSelect):
_model = models.IshtarUser
search_vector = forms.CharField(
label=_("Full text search"), widget=widgets.SearchWidget(
'ishtar-common', 'ishtaruser'
))
username = forms.CharField(label=_("Username"), max_length=200)
name = forms.CharField(label=_("Name"), max_length=200)
surname = forms.CharField(label=_("Surname"), max_length=50)
email = forms.CharField(label=_("Email"), max_length=75)
person_types = forms.ChoiceField(label=_("Type"), choices=[])
attached_to = forms.IntegerField(
label=_("Organization"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-organization'),
associated_model=models.Organization),
validators=[models.valid_id(models.Organization)])
def __init__(self, *args, **kwargs):
super(IshtarUserSelect, self).__init__(*args, **kwargs)
self.fields['person_types'].choices = models.PersonType.get_types()
class AccountFormSelection(forms.Form):
SEARCH_AND_SELECT = True
form_label = _("Account search")
associated_models = {'pk': models.IshtarUser}
currents = {'pk': models.IshtarUser}
pk = forms.IntegerField(
label="",
widget=widgets.DataTable(reverse_lazy('get-ishtaruser'),
IshtarUserSelect, models.IshtarUser),
validators=[models.valid_id(models.IshtarUser)])
class BasePersonForm(forms.ModelForm):
class Meta:
model = models.Person
fields = ['title', 'salutation', 'name', 'surname', 'address',
'address_complement', 'town', 'postal_code']
class BaseOrganizationPersonForm(forms.ModelForm):
class Meta:
model = models.Person
fields = ['attached_to', 'title', 'salutation', 'name', 'surname']
widgets = {'attached_to': widgets.JQueryPersonOrganization(
reverse_lazy('autocomplete-organization'),
reverse_lazy('organization_create'),
model=models.Organization,
attrs={'hidden': True},
new=True),
}
def __init__(self, *args, **kwargs):
super(BaseOrganizationPersonForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
person = super(BaseOrganizationPersonForm, self).save(*args, **kwargs)
instance = person.attached_to
form = BaseOrganizationForm(self.data, instance=instance,
prefix=BaseOrganizationForm.form_prefix)
if form.is_valid():
orga = form.save()
if not person.attached_to:
person.attached_to = orga
person.save()
return person
class PersonForm(SimplePersonForm):
person_types = forms.MultipleChoiceField(
label=_("Person type"), choices=[], required=False,
widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
self.fields['person_types'].choices = models.PersonType.get_types(
initial=self.init_data.get('person_types'),
empty_first=False)
self.fields['person_types'].help_text = models.PersonType.get_help()
self.limit_fields()
def save(self, user, item=None):
dct = self.cleaned_data
dct['history_modifier'] = user
for key in self.associated_models.keys():
if key in dct:
if not dct[key]:
dct.pop(key)
else:
model = self.associated_models[key]
try:
dct[key] = model.objects.get(pk=dct[key])
except model.DoesNotExist:
dct.pop(key)
person_types = dct.pop('person_types')
if not item:
new_item = models.Person.objects.create(**dct)
else:
for k in dct:
setattr(item, k, dct[k])
item.save()
item.person_types.clear()
new_item = item
for pt in person_types:
new_item.person_types.add(pt)
return new_item
class NoOrgaPersonForm(PersonForm):
def __init__(self, *args, **kwargs):
super(NoOrgaPersonForm, self).__init__(*args, **kwargs)
self.fields.pop('attached_to')
class PersonTypeForm(ManageOldType, forms.Form):
form_label = _("Person type")
base_model = 'person_type'
associated_models = {'person_type': models.PersonType}
person_type = forms.MultipleChoiceField(
label=_("Person type"), choices=[], required=False,
widget = widgets.Select2Multiple)
def __init__(self, *args, **kwargs):
super(PersonTypeForm, self).__init__(*args, **kwargs)
self.fields['person_type'].choices = models.PersonType.get_types(
initial=self.init_data.get('person_type'),
empty_first=False)
self.fields['person_type'].help_text = models.PersonType.get_help()
class AccountForm(IshtarForm):
form_label = _("Account")
associated_models = {'pk': models.Person}
currents = {'pk': models.Person}
pk = forms.IntegerField(label="", widget=forms.HiddenInput,
required=False)
username = forms.CharField(label=_("Account"), max_length=30)
email = forms.CharField(label=_("Email"), max_length=75,
validators=[validators.validate_email])
hidden_password = forms.CharField(
label=_("New password"), max_length=128, widget=forms.PasswordInput,
required=False, validators=[validators.MinLengthValidator(4)])
hidden_password_confirm = forms.CharField(
label=_("New password (confirmation)"), max_length=128,
widget=forms.PasswordInput, required=False)
HEADERS = {
'hidden_password': FormHeader(
_("New password"),
help_message=_("Keep these fields empty if you do not want to "
"change password. On creation, if you leave these "
"fields empty, the user will not be able to "
"connect.")),
}
def __init__(self, *args, **kwargs):
person = None
if 'initial' in kwargs and 'pk' in kwargs['initial']:
try:
person = models.Person.objects.get(pk=kwargs['initial']['pk'])
account = models.IshtarUser.objects.get(person=person).user_ptr
if not kwargs['initial'].get('username'):
kwargs['initial']['username'] = account.username
if not kwargs['initial'].get('email'):
kwargs['initial']['email'] = account.email
except ObjectDoesNotExist:
pass
if 'person' in kwargs:
person = kwargs.pop('person')
super(AccountForm, self).__init__(*args, **kwargs)
if person and (person.raw_name or (person.name and person.surname)):
profile = models.IshtarSiteProfile.get_current_profile()
if person.name and person.surname:
values = [person.name.lower(), person.surname.lower()]
else:
values = person.raw_name.lower().split(" ")
if profile.account_naming_style == "FN" and len(values) > 1:
values = values[1:] + [values[0]]
self.fields['username'].initial = ".".join(values)
def clean(self):
cleaned_data = self.cleaned_data
password = cleaned_data.get("hidden_password")
if password and \
password != cleaned_data.get("hidden_password_confirm"):
raise forms.ValidationError(_("Your password and confirmation "
"password do not match."))
if not cleaned_data.get("pk"):
models.is_unique(User, 'username')(cleaned_data.get("username"))
if not password:
raise forms.ValidationError(_("You must provide a correct "
"password."))
# check username unicity
q = models.IshtarUser.objects.filter(
user_ptr__username=cleaned_data.get('username'))
if cleaned_data.get('pk'):
q = q.exclude(person__pk=cleaned_data.get('pk'))
if q.count():
raise forms.ValidationError(_("This username already exists."))
return cleaned_data
class ProfileForm(ManageOldType):
form_label = _("Profiles")
base_model = 'profile'
associated_models = {
'profile_type': models.ProfileType,
'area': models.Area
}
profile_type = forms.ChoiceField(label=_("Type"), choices=[])
area = widgets.Select2MultipleField(label=_("Areas"), required=False)
name = forms.CharField(label=_("Name"), required=False)
pk = forms.IntegerField(label=" ", widget=forms.HiddenInput, required=False)
TYPES = [
FieldType('profile_type', models.ProfileType),
FieldType('area', models.Area, is_multiple=True),
]
ProfileFormset = formset_factory(ProfileForm, can_delete=True,
formset=FormSetWithDeleteSwitches)
ProfileFormset.form_label = _("Profiles")
ProfileFormset.form_admin_name = _("Profiles")
ProfileFormset.form_slug = "profiles"
class FinalAccountForm(forms.Form):
final = True
form_label = _("Confirm")
send_password = forms.BooleanField(label=_("Send the new password by "
"email?"), required=False)
def __init__(self, *args, **kwargs):
self.is_hidden = True
super(FinalAccountForm, self).__init__(*args, **kwargs)
class ProfilePersonForm(forms.Form):
"""
Edit the current profile
"""
current_profile = forms.ChoiceField(label=_("Current profile"),
choices=[])
name = forms.CharField(label=_("Name"), required=False)
profile_type = forms.ChoiceField(label=_("Profile type"), required=False,
disabled=True, choices=[])
auto_pin = forms.BooleanField(
label=_("Pin automatically items on creation and modification"),
required=False)
display_pin_menu = forms.BooleanField(
label=_("Show pin menu"),
required=False)
duplicate_profile = forms.BooleanField(
label=_("Duplicate this profile"), required=False)
delete_profile = forms.BooleanField(
label=_("Delete this profile"), required=False,
)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
choices, initial = [], kwargs.get('initial', {})
current_profile = None
for profile in self.user.ishtaruser.person.profiles.order_by(
'name', 'profile_type__label').all():
if profile.current:
current_profile = profile
initial['current_profile'] = profile.pk
choices.append((profile.pk, str(profile)))
if current_profile:
initial['name'] = current_profile.name or \
current_profile.profile_type
initial['profile_type'] = current_profile.profile_type.pk
initial['auto_pin'] = current_profile.auto_pin
initial['display_pin_menu'] = current_profile.display_pin_menu
kwargs['initial'] = initial
super(ProfilePersonForm, self).__init__(*args, **kwargs)
self.fields['current_profile'].choices = choices
if not current_profile or \
not self.user.ishtaruser.person.profiles.filter(
profile_type=current_profile.profile_type).exclude(
pk=current_profile.pk).count():
# cannot delete the current profile if no profile of this type is
# available
self.fields.pop('delete_profile')
if not current_profile:
return
self.fields['profile_type'].choices = [
(current_profile.profile_type.pk, current_profile.profile_type.name)
]
def clean(self):
data = self.cleaned_data
q = models.UserProfile.objects.filter(
person__ishtaruser=self.user.ishtaruser,
pk=data['current_profile'])
if not q.count():
return data
profile = q.all()[0]
name = data.get('name', '')
if models.UserProfile.objects.filter(
person__ishtaruser=self.user.ishtaruser,
name=name).exclude(pk=profile.pk).count():
raise forms.ValidationError(
_("A profile with the same name exists."))
return data
def save(self, session):
q = models.UserProfile.objects.filter(
person__ishtaruser=self.user.ishtaruser,
pk=self.cleaned_data['current_profile'])
if not q.count():
return
profile = q.all()[0]
# manage deletion
if self.cleaned_data.get('delete_profile', None):
q = self.user.ishtaruser.person.profiles.filter(
profile_type=profile.profile_type).exclude(
pk=profile.pk)
if not q.count():
# cannot delete the current profile if no profile of this type
# is available
return
new_current = q.all()[0]
new_current.current = True
new_current.save()
profile.delete()
return
name = self.cleaned_data['name']
# manage duplication
if self.cleaned_data.get('duplicate_profile', None):
profile_name = profile.name or profile.profile_type.label
if name == profile_name:
name += str(_(" (duplicate)"))
profile.duplicate(name=name)
return
profile.current = True
profile.name = name
profile.auto_pin = self.cleaned_data['auto_pin']
profile.display_pin_menu = self.cleaned_data['display_pin_menu']
profile.save()
clean_session_cache(session)
class TownForm(forms.Form):
form_label = _("Towns")
base_model = 'town'
associated_models = {'town': models.Town}
town = get_town_field(required=False)
class TownFormSet(FormSet):
def clean(self):
"""Checks that no towns are duplicated."""
return self.check_duplicate(('town',),
_("There are identical towns."))
TownFormset = formset_factory(TownForm, can_delete=True, formset=TownFormSet)
TownFormset.form_label = _("Towns")
TownFormset.form_admin_name = _("Towns")
TownFormset.form_slug = "towns"
class MergeFormSet(BaseModelFormSet):
from_key = ''
to_key = ''
def __init__(self, *args, **kwargs):
self._cached_list = []
super(MergeFormSet, self).__init__(*args, **kwargs)
def merge(self):
for form in self.initial_forms:
form.merge()
def initial_form_count(self):
"""
Recopied from django source only get_queryset is changed
"""
if not (self.data or self.files):
return len(self.get_restricted_queryset())
return super(MergeFormSet, self).initial_form_count()
def _construct_form(self, i, **kwargs):
"""
Recopied from django source only get_queryset is changed
"""
if self.is_bound and i < self.initial_form_count():
# Import goes here instead of module-level because importing
# django.db has side effects.
# from django.db import connections
pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name)
pk = self.data[pk_key]
"""pk_field = self.model._meta.pk
pk = pk_field.get_db_prep_lookup('exact', pk,
connection=connections[self.get_queryset().db])"""
pk = self.get_restricted_queryset()[i].pk
if isinstance(pk, list):
pk = pk[0]
kwargs['instance'] = self._existing_object(pk)
if i < self.initial_form_count() and not kwargs.get('instance'):
kwargs['instance'] = self.get_restricted_queryset()[i]
if i >= self.initial_form_count() and self.initial_extra:
# Set initial values for extra forms
try:
kwargs['initial'] = \
self.initial_extra[i - self.initial_form_count()]
except IndexError:
pass
return super(BaseModelFormSet, self)._construct_form(i, **kwargs)
def get_restricted_queryset(self):
"""
Filter (from, to) when (to, from) is already here
"""
q = self.queryset
if self._cached_list:
return self._cached_list
existing, res = [], []
# only get one version of each couple
for item in q.all():
tpl = [getattr(item, self.from_key).pk,
getattr(item, self.to_key).pk]
if tpl not in existing:
res.append(item)
existing.append(list(reversed(tpl)))
self._cached_list = res
return res
class MergeForm(forms.ModelForm):
id = forms.IntegerField(
label="", widget=forms.HiddenInput, required=False)
a_is_duplicate_b = forms.BooleanField(required=False)
b_is_duplicate_a = forms.BooleanField(required=False)
not_duplicate = forms.BooleanField(required=False)
def clean(self):
checked = [True for k in ['a_is_duplicate_b', 'b_is_duplicate_a',
'not_duplicate'] if self.cleaned_data.get(k)]
if len(checked) > 1:
raise forms.ValidationError(_("Only one choice can be checked."))
return self.cleaned_data
def merge(self, *args, **kwargs):
try:
to_item = getattr(self.instance, self.TO_KEY)
from_item = getattr(self.instance, self.FROM_KEY)
except ObjectDoesNotExist:
return
if self.cleaned_data.get('a_is_duplicate_b'):
to_item.merge(from_item)
elif self.cleaned_data.get('b_is_duplicate_a'):
from_item.merge(to_item)
elif self.cleaned_data.get('not_duplicate'):
from_item.merge_exclusion.add(to_item)
else:
return
try:
self.instance.__class__.objects.get(
**{self.TO_KEY: from_item,
self.FROM_KEY: to_item}).delete()
except ObjectDoesNotExist:
pass
self.instance.delete()
class MergePersonForm(MergeForm):
class Meta:
model = models.Person
fields = []
FROM_KEY = 'from_person'
TO_KEY = 'to_person'
class MergeOrganizationForm(MergeForm):
class Meta:
model = models.Organization
fields = []
FROM_KEY = 'from_organization'
TO_KEY = 'to_organization'
def get_image_help():
if not settings.IMAGE_MAX_SIZE:
return max_size_help()
return str(
_("Heavy images are resized to: %(width)dx%(height)d "
"(ratio is preserved).") % {
'width': settings.IMAGE_MAX_SIZE[0],
'height': settings.IMAGE_MAX_SIZE[1]}) + " " + str(max_size_help())
#######################
# Document management #
#######################
class AddGenericForm(ManageOldType, NewItemForm):
model = None # to be defined
label = forms.CharField(label=_("Label"), max_length=200)
def clean_label(self):
value = self.cleaned_data.get('label', None).strip()
if self.model.objects.filter(label=value).count():
raise forms.ValidationError(_("This value already exist"))
return value
def save(self, user):
label = self.cleaned_data['label']
base_slug = slugify(label)
slug = base_slug
idx = 0
while self.model.objects.filter(txt_idx=slug).count():
idx += 1
slug = base_slug + "-" + str(idx)
return self.model.objects.create(label=label, txt_idx=slug)
class AddDocumentTagForm(AddGenericForm):
model = models.DocumentTag
form_label = _("Document tag")
def max_value_current_year(value):
return MaxValueValidator(datetime.date.today().year)(value)
class DocumentForm(forms.ModelForm, CustomForm, ManageOldType):
form_label = _("Documentation")
form_admin_name = _("Document - General")
form_slug = "document-general"
file_upload = True
extra_form_modals = ["author", "person", "organization", "documenttag",
"container"]
associated_models = {'source_type': models.SourceType,
'support_type': models.SupportType,
'publisher': models.Organization,
'format_type': models.Format}
pk = forms.IntegerField(label="", required=False, widget=forms.HiddenInput)
title = forms.CharField(label=_("Title"), required=False,
validators=[validators.MaxLengthValidator(200)])
source_type = widgets.ModelChoiceField(
model=models.SourceType, label=_("Type"), choices=[],
required=False)
support_type = widgets.ModelChoiceField(
model=models.SupportType, label=_("Medium"), choices=[],
required=False)
format_type = widgets.ModelChoiceField(
model=models.Format, label=_("Format"), choices=[],
required=False)
scale = forms.CharField(label=_("Scale"), max_length=30, required=False)
container_id = forms.IntegerField(
label=_("Current container"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-container'),
associated_model=Container, new=True),
validators=[models.valid_id(Container)], required=False)
container_ref_id = forms.IntegerField(
label=_("Reference container"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-container'),
associated_model=Container, new=True),
validators=[models.valid_id(Container)], required=False)
authors = widgets.Select2MultipleField(
label=_("Authors"), required=False, model=models.Author,
remote="autocomplete-author")
publisher = forms.IntegerField(
label=_("Publisher"),
widget=widgets.JQueryAutoComplete(
reverse_lazy(
'autocomplete-organization',
args=[models.organization_type_pks_lazy(
settings.ISHTAR_SLUGS["document-publisher"])]),
limit={
'organization_type': [models.organization_type_pks_lazy(
settings.ISHTAR_SLUGS["document-publisher"])]},
tips=models.get_publisher_label,
associated_model=models.Organization),
validators=[models.valid_id(models.Organization)], required=False)
publishing_year = forms.IntegerField(
label=_("Year of publication"),
validators=[MinValueValidator(1000), max_value_current_year],
required=False)
licenses = widgets.Select2MultipleField(
label=_("Licenses"), required=False, model=models.LicenseType)
tags = widgets.Select2MultipleField(
label=_("Tags"), required=False, model=models.DocumentTag,
remote="autocomplete-documenttag")
language = widgets.ModelChoiceField(
model=models.Language, label=_("Language"), choices=[],
required=False)
issn = forms.CharField(
label=_("ISSN"),
widget=widgets.ISSNWidget,
validators=[validators.MaxLengthValidator(9)], required=False)
isbn = forms.CharField(
label=_("ISBN"),
widget=widgets.ISBNWidget,
validators=[validators.MaxLengthValidator(17)], required=False)
source = widgets.ModelJQueryAutocompleteField(
label=_("Source"),
model=models.Document, required=False)
source_free_input = forms.CharField(
label=_("Source - free input"),
validators=[validators.MaxLengthValidator(500)], required=False)
source_page_range = forms.CharField(
label=_("Source - page range"),
validators=[validators.MaxLengthValidator(500)], required=False,
help_text=_("Unique page: \"242\", page range: \"242-245\", multiple "
"pages: \"242;245;249\", multiples pages and multiple "
"pages ranges: \"242-245;249;262-265\".")
)
associated_url = forms.URLField(
max_length=1000, required=False,
label=_("Numerical ressource (web address)"))
image = forms.ImageField(
label=_("Image"), help_text=mark_safe(get_image_help()),
max_length=255, required=False, widget=widgets.ImageFileInput(),
validators=[file_size_validator]
)
associated_file = forms.FileField(
label=pgettext("Not directory", "File"), max_length=255,
required=False, help_text=max_size_help(),
validators=[file_size_validator]
)
reference = forms.CharField(
label=_("Reference"),
validators=[validators.MaxLengthValidator(100)], required=False)
internal_reference = forms.CharField(
label=_("Internal reference"),
validators=[validators.MaxLengthValidator(100)], required=False)
receipt_date = forms.DateField(label=_("Receipt date"), required=False,
widget=DatePicker)
creation_date = forms.DateField(label=_("Creation date"), required=False,
widget=DatePicker)
receipt_date_in_documentation = forms.DateField(
label=_("Receipt date in documentation"), required=False,
widget=DatePicker)
comment = forms.CharField(label=_("Comment"), widget=forms.Textarea,
required=False)
description = forms.CharField(label=_("Description"),
widget=forms.Textarea, required=False)
additional_information = forms.CharField(
label=_("Additional information"), widget=forms.Textarea,
required=False)
duplicate = forms.NullBooleanField(label=_("Has a duplicate"),
required=False)
TYPES = [
FieldType('source_type', models.SourceType),
FieldType('support_type', models.SupportType),
FieldType('format_type', models.Format),
FieldType('language', models.Language),
FieldType('licences', models.LicenseType, is_multiple=True),
FieldType('tags', models.DocumentTag, is_multiple=True),
]
class Meta:
model = models.Document
fields = [
'title', 'source_type', 'reference', 'internal_reference',
'format_type', 'support_type', 'scale',
'image', 'associated_file', 'associated_url', 'tags',
'authors', 'receipt_date',
'receipt_date_in_documentation', 'creation_date',
'publisher', 'publishing_year',
'language', 'isbn', 'issn', 'licenses',
'source', 'source_free_input', 'source_page_range',
'container_id', "container_ref_id",
'comment', 'description', 'additional_information', 'duplicate'
]
HEADERS = {
'finds': FormHeader(_("Related items")),
'title': FormHeader(_("Identification")),
'format_type': FormHeader(_("Format")),
'image': FormHeader(_("Content")),
'authors': FormHeader(_("Authors")),
'receipt_date': FormHeader(_("Dates")),
'publisher': FormHeader(_("Publishing"), collapse=True),
'source': FormHeader(_("Source"), collapse=True),
'container_id': FormHeader(_("Warehouse"), collapse=True),
'comment': FormHeader(_("Advanced"), collapse=True),
}
OPTIONS_PERMISSIONS = [
# field name, permission, options
("tags", ("ishtar_common.add_documenttag",), {"new": True}),
("authors", ("ishtar_common.add_author",), {"new": True}),
("publisher", ("ishtar_common.add_organization",), {"new": True}),
("container", ("archaeological_warehouse.add_container",),
{"new": True}),
("container_ref", ("archaeological_warehouse.add_container",),
{"new": True}),
]
def __init__(self, *args, **kwargs):
main_items_fields = {}
if "main_items_fields" in kwargs:
main_items_fields = kwargs.pop("main_items_fields")
self.user = None
if kwargs.get("user", None):
self.user = kwargs.pop("user")
self.is_instancied = bool(kwargs.get('instance', False))
super(DocumentForm, self).__init__(*args, **kwargs)
fields = OrderedDict()
for related_key in models.Document.RELATED_MODELS_ALT:
model = models.Document._meta.get_field(related_key).related_model
fields[related_key] = widgets.Select2MultipleField(
model=model, remote=True, label=model._meta.verbose_name_plural,
required=False, style="width: 100%"
)
if related_key in main_items_fields:
for field_key, label in main_items_fields[related_key]:
disabled = False
if kwargs.get('initial', None) and kwargs['initial'].get(
field_key, False):
disabled = True
fields[field_key] = forms.BooleanField(
label=label, required=False, disabled=disabled)
for k in self.fields:
fields[k] = self.fields[k]
self.fields = fields
def clean_source_page_range(self):
value = self.cleaned_data.get(
'source_page_range', None).replace(" ", "")
if value and not re.match(r"^(\d+[-;]*\d)+$", value):
raise forms.ValidationError(
_("Incorrect page range."))
return value
def get_headers(self):
headers = self.HEADERS.copy()
if self.is_instancied:
headers["finds"] = FormHeader(headers["finds"].label, collapse=True)
return headers
def get_conditional_filter_fields(self):
"""
Helper to get values for filtering select widget on select by another
widget
:return: conditional_fields, excluded_fields, all_values
* conditional_fields:
{input_key: {
input_pk: [(output_key1, "pk1,pk2,..."),
(output_key2, "pk1,pk2,...")],
input_pk2: ...
},
input_key2: {...}
}
* excluded_fields: {output_key: "pk1,pk2,...", ...} # list pk for all
output_key in condition_fields
* all_values: {output_key: [(pk1, label1), (pk2, label2), ...]}
"""
conditional_fields = {}
excluded_fields = {}
key = 'source_type'
for doc_type in models.SourceType.objects.filter(
available=True, formats__pk__isnull=False).all():
if key not in conditional_fields:
conditional_fields[key] = {}
sub_key = doc_type.pk
if sub_key in conditional_fields[key]:
continue
lst = [str(f.pk) for f in models.Format.objects.filter(
available=True, document_types__pk=doc_type.pk)]
if 'format_type' not in excluded_fields:
excluded_fields['format_type'] = []
for k in lst:
if k not in excluded_fields['format_type']:
excluded_fields['format_type'].append(k)
conditional_fields[key][sub_key] = [('format_type', ",".join(lst))]
for doc_type in models.SourceType.objects.filter(
available=True, supports__pk__isnull=False).all():
if key not in conditional_fields:
conditional_fields[key] = {}
lst = [str(f.pk) for f in models.SupportType.objects.filter(
available=True, document_types__pk=doc_type.pk)]
if 'support_type' not in excluded_fields:
excluded_fields['support_type'] = []
for k in lst:
if k not in excluded_fields['support_type']:
excluded_fields['support_type'].append(k)
sub_key = doc_type.pk
if sub_key not in conditional_fields[key]:
conditional_fields[key][sub_key] = []
conditional_fields[key][sub_key].append(
('support_type', ",".join(lst)))
for k in excluded_fields:
excluded_fields[k] = ",".join(excluded_fields[k])
all_values = {
"format_type": [list(tp) for tp in models.Format.get_types()],
"support_type": [list(tp) for tp in models.SupportType.get_types()]
}
return conditional_fields, excluded_fields, all_values
def clean(self):
cleaned_data = self.cleaned_data
if not cleaned_data.get('title', None) and \
not cleaned_data.get('image', None) and \
not cleaned_data.get('associated_file', None) and \
not cleaned_data.get('associated_url', None):
raise forms.ValidationError(_("You should at least fill one of "
"this field: title, url, image or "
"file."))
for rel in models.Document.RELATED_MODELS:
if cleaned_data.get(rel, None):
return cleaned_data
raise forms.ValidationError(_("A document has to be attached at least "
"to one item"))
def clean_publisher(self):
if not self.cleaned_data.get("publisher", None):
return
try:
return models.Organization.objects.get(
pk=self.cleaned_data["publisher"])
except models.Organization.DoesNotExist:
return
def save(self, commit=True):
if not self.cleaned_data.get('authors', None):
self.cleaned_data['authors'] = []
item = super(DocumentForm, self).save(commit=commit)
for related_key in models.Document.RELATED_MODELS:
related = getattr(item, related_key)
initial = dict([(rel.pk, rel) for rel in related.all()])
new = [int(pk)
for pk in sorted(self.cleaned_data.get(related_key, []))]
for pk, value in initial.items():
if pk in new:
continue
related.remove(value)
for new_pk in new:
related_item = related.model.objects.get(pk=new_pk)
if new_pk not in initial.keys():
related.add(related_item)
key = "{}_{}_main_image".format(related_key, related_item.pk)
if self.cleaned_data.get(key, []) and \
related_item.main_image != item:
related_item.skip_history_when_saving = True
related_item.main_image = item
related_item.save()
item = models.Document.objects.get(pk=item.pk)
if self.user:
item.history_creator = self.user
item.history_modifier = self.user
item.skip_history_when_saving = True
item.save() # resave to regen the attached items
return item
class DocumentSelect(HistorySelect):
_model = models.Document
form_admin_name = _("Document - 001 - Search")
form_slug = "document-001-search"
search_vector = forms.CharField(
label=_("Full text search"), widget=widgets.SearchWidget(
'ishtar-common', 'document'
))
authors = forms.IntegerField(
widget=widgets.JQueryAutoComplete(
"/" + settings.URL_PATH + 'autocomplete-author',
associated_model=models.Author),
validators=[models.valid_id(models.Author)], label=_("Author"),
required=False)
title = forms.CharField(label=_("Title"))
source_type = forms.ChoiceField(label=_("Type"), choices=[])
reference = forms.CharField(label=_("Reference"))
internal_reference = forms.CharField(label=_("Internal reference"))
description = forms.CharField(label=_("Description"))
format = forms.ChoiceField(label=_("Format"), choices=[])
support = forms.ChoiceField(label=_("Medium"), choices=[])
scale = forms.CharField(label=_("Scale"))
associated_url = forms.CharField(label=_("Web address"))
tag = forms.ChoiceField(label=_("Tag"), choices=[])
publisher = forms.IntegerField(
label=_("Publisher"),
widget=widgets.JQueryAutoComplete(
reverse_lazy(
'autocomplete-organization',
args=[models.organization_type_pks_lazy(
settings.ISHTAR_SLUGS["document-publisher"])]),
limit={
'organization_type': [models.organization_type_pks_lazy(
settings.ISHTAR_SLUGS["document-publisher"])]},
tips=models.get_publisher_label,
associated_model=models.Organization),
validators=[models.valid_id(models.Organization)])
publishing_year = forms.IntegerField(label=_("Year of publication"))
language = forms.ChoiceField(label=_("Language"), choices=[])
isbn = forms.CharField(label=_("ISBN"))
issn = forms.CharField(label=_("ISSN"))
licenses = forms.ChoiceField(label=_("License"), choices=[])
comment = forms.CharField(label=_("Comment"))
additional_information = forms.CharField(
label=_("Additional informations"))
duplicate = forms.NullBooleanField(label=_("Has a duplicate"))
associated_file__isnull = forms.NullBooleanField(label=_("Has a file?"))
image__isnull = forms.NullBooleanField(label=_("Has an image?"))
source = forms.IntegerField(
label=_("Source"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-document'),
associated_model=models.Document),
validators=[models.valid_id(models.Document)])
source_free_input = forms.CharField(
label=_("Source - free input"))
warehouse_container = forms.IntegerField(
label=_("Warehouse - Container"), required=False,
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-container'),
associated_model=Container),
validators=[models.valid_id(Container)])
warehouse_container_ref = forms.IntegerField(
label=_("Warehouse - Reference container"), required=False,
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-container'),
associated_model=Container),
validators=[models.valid_id(Container)])
operation = forms.IntegerField(
label=_("Operation"), required=False,
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-operation'),
associated_model=Operation),
validators=[models.valid_id(Operation)])
context_record = forms.IntegerField(
label=_("Context record"), required=False,
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-contextrecord'),
associated_model=ContextRecord),
validators=[models.valid_id(ContextRecord)])
find_basket = forms.IntegerField(
label=_("Basket - Finds"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-findbasket'),
associated_model=FindBasket),
validators=[models.valid_id(FindBasket)], required=False)
find = forms.IntegerField(
label=_("Find"), required=False,
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-find'),
associated_model=Find),
validators=[models.valid_id(Find)])
find__denomination = forms.CharField(label=_("Find - denomination"),
required=False)
containers = forms.IntegerField(
label=_("Container"), required=False,
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-container'),
associated_model=Container),
validators=[models.valid_id(Container)])
receipt_date__before = forms.DateField(
label=_("Receipt date before"), widget=DatePicker)
receipt_date__after = forms.DateField(
label=_("Receipt date after"), widget=DatePicker)
creation_date__before = forms.DateField(
label=_("Creation date before"), widget=DatePicker)
creation_date__after = forms.DateField(
label=_("Creation date after"), widget=DatePicker)
receipt_date_in_documentation__before = forms.DateField(
label=_("Receipt date before"), widget=DatePicker)
receipt_date_in_documentation__after = forms.DateField(
label=_("Receipt date after"), widget=DatePicker)
TYPES = [
FieldType('source_type', models.SourceType),
FieldType('format', models.Format),
FieldType('support', models.SupportType),
FieldType('tag', models.DocumentTag),
FieldType('language', models.Language),
FieldType('licenses', models.LicenseType),
]
PROFILE_FILTER = {
'context_record': ['context_record'],
'find': ['find'],
'warehouse': ['container']
}
class DocumentFormSelection(LockForm, CustomFormSearch):
SEARCH_AND_SELECT = True
form_label = _("Document search")
associated_models = {'pk': models.Document}
currents = {'pk': models.Document}
pk = forms.IntegerField(
label="", required=False,
widget=widgets.DataTable(
reverse_lazy('get-document'), DocumentSelect,
models.Document,
gallery=True
),
validators=[models.valid_id(models.Document)])
class DocumentFormMultiSelection(LockForm, MultiSearchForm):
form_label = _("Document search")
associated_models = {'pks': models.Document}
pk_key = 'pks'
pk = forms.CharField(
label="", required=False,
widget=widgets.DataTable(
reverse_lazy('get-document'), DocumentSelect,
models.Document,
multiple_select=True,
gallery=True
),
validators=[models.valid_ids(models.Document)])
class QADocumentFormMulti(QAForm):
form_admin_name = _("Document - Quick action - Modify")
form_slug = "document-quickaction-modify"
base_models = ['qa_source_type']
associated_models = {
'qa_source_type': models.SourceType,
'qa_authors': models.Author,
}
MULTI = True
REPLACE_FIELDS = [
'qa_source_type',
'qa_creation_date',
]
qa_source_type = forms.ChoiceField(
label=_("Source type"), required=False
)
qa_authors = widgets.ModelJQueryAutocompleteField(
model=models.Author, label=_("Author"), new=True,
required=False)
qa_creation_date = forms.DateField(
label=_("Creation date"), widget=DatePicker, required=False)
TYPES = [
FieldType('qa_source_type', models.SourceType),
]
def _get_qa_authors(self, value):
try:
value = models.Author.objects.get(pk=value).cached_label
except models.Author.DoesNotExist:
return ""
return value
class QADocumentDuplicateForm(IshtarForm):
qa_title = forms.CharField(label=_("Reference"), max_length=500,
required=False)
qa_source_type = forms.ChoiceField(label=_("Type"), choices=[],
required=False)
TYPES = [
FieldType('qa_source_type', models.SourceType),
]
def __init__(self, *args, **kwargs):
self.user = None
if 'user' in kwargs:
self.user = kwargs.pop('user')
if hasattr(self.user, 'ishtaruser'):
self.user = self.user.ishtaruser
self.document = kwargs.pop('items')[0]
super(QADocumentDuplicateForm, self).__init__(*args, **kwargs)
self.fields['qa_title'].initial = self.document.title + str(
_(" - duplicate"))
if self.document.source_type:
self.fields['qa_source_type'].initial = self.document.source_type.pk
for related_key in models.Document.RELATED_MODELS_ALT:
related = getattr(self.document, related_key)
if not related.count():
continue
model = models.Document._meta.get_field(related_key).related_model
initial = [item.pk for item in related.all()]
self.fields["qa_" + related_key] = widgets.Select2MultipleField(
model=model, remote=True, label=model._meta.verbose_name_plural,
required=False, long_widget=True, initial=initial
)
def save(self):
data = {"index": None}
for k in ["title"]:
data[k] = self.cleaned_data.get("qa_" + k, None)
if self.cleaned_data.get("qa_source_type", None):
try:
data["source_type"] = models.SourceType.objects.get(
pk=int(self.cleaned_data["qa_source_type"]), available=True)
except models.SourceType.DoesNotExist:
return
new = self.document.duplicate_item(self.user, data=data)
for related_key in models.Document.RELATED_MODELS_ALT:
getattr(new, related_key).clear()
values = self.cleaned_data.get("qa_" + related_key, [])
model = models.Document._meta.get_field(related_key).related_model
for value in values:
getattr(new, related_key).add(model.objects.get(pk=value))
new.skip_history_when_saving = True
new._cached_label_checked = False
new._search_updated = False
new._no_move = True
new.save() # regen of labels
return new
class QADocumentPackagingForm(IshtarForm):
container = forms.IntegerField(
label=_("Container"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-container'),
associated_model=Container, new=True),
validators=[models.valid_id(Container)])
container_to_change = forms.ChoiceField(
label=_("Change "), required=True,
choices=(
('current-and-reference', _("current and reference containers")),
('reference', _("the reference container")),
('current', _("the current container")),
)
)
def __init__(self, *args, **kwargs):
self.confirm = False
self.user = None
if 'user' in kwargs:
self.user = kwargs.pop('user')
if hasattr(self.user, 'ishtaruser'):
self.user = self.user.ishtaruser
self.items = kwargs.pop('items')
super(QADocumentPackagingForm, self).__init__(*args, **kwargs)
def save(self, items, user):
container = Container.objects.get(pk=self.cleaned_data['container'])
container_to_change = self.cleaned_data.get('container_to_change', '')
container_attrs = []
if container_to_change in ('reference', 'current-and-reference'):
container_attrs.append('container_ref')
if container_to_change in ('current', 'current-and-reference'):
container_attrs.append('container')
for document in items:
changed = False
for container_attr in container_attrs:
if getattr(document, container_attr) == container:
continue
setattr(document, container_attr, container)
changed = True
if changed:
document.history_modifier = user
document.save()
class QALockForm(forms.Form):
action = forms.ChoiceField(
label=_("Action"), choices=(('lock', _("Lock")),
('unlock', _("Unlock"))))
def __init__(self, *args, **kwargs):
self.items = kwargs.pop('items')
super(QALockForm, self).__init__(*args, **kwargs)
def save(self, items, user):
locked = self.cleaned_data["action"] == "lock"
for item in items:
item.locked = locked
item.lock_user = user if locked else None
item.skip_history_when_saving = True
item.save()
class SourceDeletionForm(FinalForm):
confirm_msg = " "
confirm_end_msg = _("Would you like to delete this documentation?")
######################
# Authors management #
######################
class AuthorForm(ManageOldType, NewItemForm):
form_label = _("Author")
associated_models = {'person': models.Person,
'author_type': models.AuthorType}
person = forms.IntegerField(
widget=widgets.JQueryAutoComplete(
"/" + settings.URL_PATH + 'autocomplete-person',
associated_model=models.Person, new=True),
validators=[models.valid_id(models.Person)], label=_("Person"))
author_type = forms.ChoiceField(label=_("Author type"), choices=[])
def __init__(self, *args, **kwargs):
super(AuthorForm, self).__init__(*args, **kwargs)
self.fields['author_type'].choices = models.AuthorType.get_types(
initial=self.init_data.get('author_type'))
self.limit_fields()
def clean(self):
person_id = self.cleaned_data.get("person", None)
author_type_id = self.cleaned_data.get("author_type", None)
if not person_id or not author_type_id:
return self.cleaned_data
if models.Author.objects.filter(author_type_id=author_type_id,
person_id=person_id).count():
raise forms.ValidationError(_("This author already exist."))
def save(self, user):
dct = self.cleaned_data
dct['author_type'] = models.AuthorType.objects.get(
pk=dct['author_type'])
dct['person'] = models.Person.objects.get(pk=dct['person'])
new_item = models.Author(**dct)
new_item.save()
return new_item
class AuthorFormSelection(forms.Form):
form_label = _("Author selection")
base_model = 'author'
associated_models = {'author': models.Author}
author = forms.IntegerField(
required=False,
widget=widgets.JQueryAutoComplete(
"/" + settings.URL_PATH + 'autocomplete-author',
associated_model=models.Author, new=True),
validators=[models.valid_id(models.Author)], label=_("Author"))
class AuthorFormSet(FormSet):
def clean(self):
"""Checks that no author are duplicated."""
return self.check_duplicate(('author',),
_("There are identical authors."))
AuthorFormset = formset_factory(AuthorFormSelection, can_delete=True,
formset=AuthorFormSet)
AuthorFormset.form_label = _("Authors")
AuthorFormset.form_admin_name = _("Authors")
AuthorFormset.form_slug = "authors"
class SearchQueryForm(forms.Form):
query = forms.CharField(max_length=None, label=_("Query"), initial='*',
widget=forms.HiddenInput)
search_query = forms.ChoiceField(label="", required=False,
choices=[])
label = forms.CharField(label="", max_length=None, required=False)
is_alert = forms.BooleanField(label=_("Is an alert"), required=False)
create_or_update = forms.ChoiceField(
choices=(('create', _("Create")),
('update', _("Update"))), initial='create')
def __init__(self, profile, content_type, *args, **kwargs):
self.profile = profile
self.content_type = content_type
super(SearchQueryForm, self).__init__(*args, **kwargs)
self.fields['search_query'].choices = [
(c.pk, c.label) for c in models.SearchQuery.objects.filter(
content_type=content_type, profile=profile).all()]
if not self.fields['search_query'].choices:
self.fields.pop('search_query')
def clean(self):
data = self.cleaned_data
if data['create_or_update'] == 'create' and not data['label']:
raise forms.ValidationError(_("A label is required for a new "
"search query."))
elif data['create_or_update'] == 'update':
if not data['search_query']:
raise forms.ValidationError(_("Select the search query to "
"update"))
q = models.SearchQuery.objects.filter(
profile=self.profile, content_type=self.content_type,
pk=data['search_query'])
if not q.count():
raise forms.ValidationError(_("Query does not exist."))
return data
def save(self):
data = self.cleaned_data
if data['create_or_update'] == 'create':
sq = models.SearchQuery.objects.create(
label=data['label'], query=data['query'], profile=self.profile,
content_type=self.content_type, is_alert=data['is_alert'])
else:
try:
sq = models.SearchQuery.objects.get(
profile=self.profile, content_type=self.content_type,
pk=data['search_query'])
except models.SearchQuery.DoesNotExist:
raise forms.ValidationError(_("Query does not exist."))
sq.query = data['query']
sq.save()
return sq
class QRSearchForm(forms.Form):
query = forms.CharField(max_length=None, label=_("Query"), initial='*')
current_url = forms.CharField(max_length=None, label="",
widget=forms.HiddenInput())
def save(self):
data = self.cleaned_data
url = data["current_url"]
parsed_url = urlparse(url)
base_url = "{}://{}".format(parsed_url.scheme, parsed_url.netloc)
url = base_url + parsed_url.path
url += "?stored_search=" + quote(data["query"])
tiny_url = models.TinyUrl.objects.create(link=url)
short_url = base_url + reverse('tiny-redirect',
args=[tiny_url.get_short_id()])
qr = pyqrcode.create(short_url, version=settings.ISHTAR_QRCODE_VERSION)
tmpdir = tempfile.mkdtemp("-qrcode")
date = datetime.datetime.today().isoformat().replace(
":", "-").replace(".", "")
base_filename = '{}-qrcode.png'.format(date)
filename = os.path.join(tmpdir, base_filename)
qr.png(filename, scale=settings.ISHTAR_QRCODE_SCALE)
dest_dir = os.path.join(settings.MEDIA_ROOT, "tmp")
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
shutil.move(filename, dest_dir)
return os.path.join(settings.MEDIA_URL, "tmp", base_filename)
|