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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2013 É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.
"""
Administrative forms definitions: manage accounts and persons
"""
import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import validators
from django.core.mail import send_mail
from django.core.exceptions import ObjectDoesNotExist
from django.forms.formsets import formset_factory, DELETION_FIELD_NAME
from django.forms.models import BaseModelFormSet
from django.template import Context, RequestContext, loader
from django.shortcuts import render_to_response
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
import models
import widgets
from forms import FinalForm, FormSet, reverse_lazy, name_validator, TableSelect
def get_town_field(label=_(u"Town"), required=True):
help_text = _(u"<p>Type name, department code and/or postal code of the "
u"town you would like to select. The search is insensitive to case.</p>\n"
u"<p>Only the first twenty results are displayed but specifying the "
u"department code is generally sufficient to get the appropriate result.</p>"
u"\n<p class='example'>For instance type \"saint denis 93\" for getting "
u"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_person_field(label=_(u"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 = [
unicode(models.PersonType.objects.get(txt_idx=person_type).pk)
for person_type in person_types]
url += u"/" + u'_'.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 = []
for value, lbl in self.fields[key].choices:
if unicode(value) in self.limits[key]:
new_choices.append((value, lbl))
self.fields[key].choices = new_choices
if len(new_choices) == 1:
self.fields[key].initial = [new_choices[0][0]]
class OrganizationForm(NewItemForm):
form_label = _(u"Organization")
associated_models = {'organization_type':models.OrganizationType}
name = forms.CharField(label=_(u"Name"), max_length=300,
validators=[name_validator])
organization_type = forms.ChoiceField(label=_(u"Organization type"),
choices=[])
address = forms.CharField(label=_(u"Address"), widget=forms.Textarea,
required=False)
address_complement = forms.CharField(label=_(u"Address complement"),
widget=forms.Textarea, required=False)
postal_code = forms.CharField(label=_(u"Postal code"), max_length=10,
required=False)
town = forms.CharField(label=_(u"Town"), max_length=30, required=False)
country = forms.CharField(label=_(u"Country"), max_length=30,
required=False)
email = forms.EmailField(label=_(u"Email"), required=False)
phone = forms.CharField(label=_(u"Phone"), max_length=18, required=False)
mobile_phone = forms.CharField(label=_(u"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()
self.fields['organization_type'].help_text = \
models.OrganizationType.get_help()
self.limit_fields()
def save(self, user):
dct = self.cleaned_data
dct['history_modifier'] = user
dct['organization_type'] = models.OrganizationType.objects.get(
pk=dct['organization_type'])
new_item = models.Organization(**dct)
new_item.save()
return new_item
class OrganizationSelect(TableSelect):
name = forms.CharField(label=_(u"Name"), max_length=300)
organization_type = forms.ChoiceField(label=_(u"Type"), choices=[])
def __init__(self, *args, **kwargs):
super(OrganizationSelect, self).__init__(*args, **kwargs)
self.fields['organization_type'].choices = \
models.OrganizationType.get_types()
class OrganizationFormSelection(forms.Form):
form_label = _(u"Organization search")
associated_models = {'pk':models.Organization}
currents = {'pk':models.Organization}
pk = forms.IntegerField(label="",
widget=widgets.JQueryJqGrid(reverse_lazy('get-organization'),
OrganizationSelect, models.Organization),
validators=[models.valid_id(models.Organization)])
class PersonSelect(TableSelect):
name = forms.CharField(label=_(u"Name"), max_length=30)
surname = forms.CharField(label=_(u"Surname"), max_length=20)
email = forms.CharField(label=_(u"Email"), max_length=75)
person_types = forms.ChoiceField(label=_(u"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(forms.Form):
form_label = _(u"Person search")
associated_models = {'pk':models.Person}
currents = {'pk':models.Person}
pk = forms.IntegerField(label="",
widget=widgets.JQueryJqGrid(reverse_lazy('get-person'),
PersonSelect, models.Person),
validators=[models.valid_id(models.Person)])
class SimplePersonForm(NewItemForm):
form_label = _("Identity")
associated_models = {'attached_to':models.Organization}
title = forms.ChoiceField(label=_("Title"), choices=models.Person.TYPE)
surname = forms.CharField(label=_(u"Surname"), max_length=20,
validators=[name_validator])
name = forms.CharField(label=_(u"Name"), max_length=30,
validators=[name_validator])
address = forms.CharField(label=_(u"Address"), widget=forms.Textarea,
required=False)
address_complement = forms.CharField(label=_(u"Address complement"),
widget=forms.Textarea, required=False)
postal_code = forms.CharField(label=_(u"Postal code"), max_length=10,
required=False)
town = forms.CharField(label=_(u"Town"), max_length=30, required=False)
country = forms.CharField(label=_(u"Country"), max_length=30,
required=False)
email = forms.EmailField(label=_(u"Email"), required=False)
phone = forms.CharField(label=_(u"Phone"), max_length=18, required=False)
mobile_phone = forms.CharField(label=_(u"Town"), 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)
class PersonForm(SimplePersonForm):
person_types = forms.MultipleChoiceField(label=_("Person type"),
choices=[], widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
self.fields['person_types'].choices = models.PersonType.get_types(
empty_first=False)
self.fields['person_types'].help_text = models.PersonType.get_help()
self.limit_fields()
def save(self, user):
dct = self.cleaned_data
dct['history_modifier'] = user
if 'attached_to' in dct and dct['attached_to']:
dct['attached_to'] = models.Organization.objects.get(
pk=dct['attached_to'])
person_types = dct.pop('person_types')
new_item = models.Person.objects.create(**dct)
for pt in person_types:
new_item.person_types.add(pt)
return new_item
class PersonTypeForm(forms.Form):
form_label = _("Person type")
base_model = 'person_type'
associated_models = {'person_type':models.PersonType}
person_type = forms.MultipleChoiceField(label=_("Person type"),
choices=[], widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
super(PersonTypeForm, self).__init__(*args, **kwargs)
self.fields['person_type'].choices = models.PersonType.get_types(
empty_first=False)
self.fields['person_type'].help_text = models.PersonType.get_help()
class AccountForm(forms.Form):
form_label = _("Account")
associated_models = {'pk':models.Person}
currents = {'pk':models.Person}
pk = forms.IntegerField(label=u"", widget=forms.HiddenInput, required=False)
username = forms.CharField(label=_(u"Account"), max_length=30)
email = forms.CharField(label=_(u"Email"), max_length=75,
validators=[validators.validate_email])
hidden_password = forms.CharField(label=_(u"New password"), max_length=128,
widget=forms.PasswordInput, required=False,
validators=[validators.MinLengthValidator(4)])
hidden_password_confirm = forms.CharField(
label=_(u"New password (confirmation)"), max_length=128,
widget=forms.PasswordInput, required=False)
def __init__(self, *args, **kwargs):
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)
kwargs['initial'].update({'username':account.username,
'email':account.email})
except ObjectDoesNotExist:
pass
return super(AccountForm, self).__init__(*args, **kwargs)
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(_(u"Your password and confirmation "
u"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(_(u"You must provide a correct "\
u"password."))
# check username unicity
usernames = models.IshtarUser.objects.filter(username=
cleaned_data.get('username'))
if cleaned_data.get('pk'):
usernames.exclude(pk=cleaned_data.get('pk'))
if usernames.count():
raise forms.ValidationError(_(u"This username already exists."))
return cleaned_data
class FinalAccountForm(forms.Form):
final = True
form_label = _("Confirm")
send_password = forms.BooleanField(label=_(u"Send the new password by "
u"email?"), required=False)
def __init__(self, *args, **kwargs):
self.is_hidden = True
return super(FinalAccountForm, self).__init__(*args, **kwargs)
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")
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=u"", 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(_(u"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:
reverse = 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'
######################
# Sources management #
######################
class SourceForm(forms.Form):
form_label = _(u"Documentation informations")
associated_models = {'source_type':models.SourceType}
title = forms.CharField(label=_(u"Title"),
validators=[validators.MaxLengthValidator(200)])
source_type = forms.ChoiceField(label=_(u"Source type"), choices=[])
associated_url = forms.URLField(required=False,
label=_(u"Numerical ressource (web address)"))
receipt_date = forms.DateField(label=_(u"Receipt date"), required=False,
widget=widgets.JQueryDate)
creation_date = forms.DateField(label=_(u"Creation date"), required=False,
widget=widgets.JQueryDate)
def __init__(self, *args, **kwargs):
super(SourceForm, self).__init__(*args, **kwargs)
self.fields['source_type'].choices = models.SourceType.get_types()
class SourceSelect(TableSelect):
authors = forms.IntegerField(
widget=widgets.JQueryAutoComplete("/" + settings.URL_PATH + \
'autocomplete-author', associated_model=models.Author),
validators=[models.valid_id(models.Author)], label=_(u"Author"),
required=False)
source_type = forms.ChoiceField(label=_("Source type"), choices=[])
def __init__(self, *args, **kwargs):
super(SourceSelect, self).__init__(*args, **kwargs)
self.fields['source_type'].choices = models.SourceType.get_types()
self.fields['source_type'].help_text = models.SourceType.get_help()
class SourceDeletionForm(FinalForm):
confirm_msg = " "
confirm_end_msg = _(u"Would you like to delete this documentation?")
######################
# Authors management #
######################
class AuthorForm(NewItemForm):
form_label = _(u"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=_(u"Person"))
author_type = forms.ChoiceField(label=_(u"Author type"), choices=[])
def __init__(self, *args, **kwargs):
super(AuthorForm, self).__init__(*args, **kwargs)
self.fields['author_type'].choices = models.AuthorType.get_types()
self.limit_fields()
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 = _(u"Author selection")
base_model = 'author'
associated_models = {'author':models.Author}
author = forms.IntegerField(
widget=widgets.JQueryAutoComplete("/" + settings.URL_PATH + \
'autocomplete-author', associated_model=models.Author, new=True),
validators=[models.valid_id(models.Author)], label=_(u"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")
|