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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011 É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.template import Context, RequestContext, loader
from django.shortcuts import render_to_response
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.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from ishtar import settings
import models
import widgets
from forms import Wizard, FinalForm, FormSet, reverse_lazy, name_validator,\
clean_duplicated
class PersonWizard(Wizard):
model = models.Person
class PersonFormSelection(forms.Form):
form_label = _(u"Person search")
associated_models = {'pk':models.Person}
currents = {'pk':models.Person}
pk = forms.IntegerField(label=_("Person"),
widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-person'),
associated_model=models.Person),
validators=[models.valid_id(models.Person)])
class PersonForm(forms.Form):
form_label = _("Identity")
associated_models = {'attached_to':models.Organization,
'person_type':models.PersonType}
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])
email = forms.CharField(label=_(u"Email"), max_length=40, required=False,
validators=[validators.validate_email])
person_type = forms.ChoiceField(label=_("Person type"),
choices=models.PersonType.get_types())
attached_to = forms.IntegerField(label=_("Current organization"),
widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-organization'),
associated_model=models.Organization),
validators=[models.valid_id(models.Organization)], required=False)
is_author = forms.BooleanField(label=_(u"Is an author?"),
required=False)
in_charge_storage = forms.BooleanField(required=False,
label=_(u"In charge of a storage?"))
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
self.fields['person_type'].choices = models.PersonType.get_types()
person_creation_wizard = PersonWizard([
('identity-person_creation', PersonForm),
('final-person_creation', FinalForm)],
url_name='person_creation',)
person_modification_wizard = PersonWizard([
('selec-person_modification', PersonFormSelection),
('identity-person_modification', PersonForm),
('final-person_modification', FinalForm)],
url_name='person_modification',)
class AccountWizard(Wizard):
model = models.Person
def get_formated_datas(self, forms):
datas = super(AccountWizard, self).get_formated_datas(forms)
for form in forms:
if not hasattr(form, "cleaned_data"):
continue
for key in form.cleaned_data:
if key == 'hidden_password' and form.cleaned_data[key]:
datas[-1][1].append((_("New password"), "*"*8))
return datas
def done(self, request, storage, form_list, **kwargs):
'''
Save the account
'''
dct = {}
for form in form_list:
if not form.is_valid():
return self.render(request, storage, form)
associated_models = hasattr(form, 'associated_models') and \
form.associated_models or {}
if type(form.cleaned_data) == dict:
for key in form.cleaned_data:
if key == 'pk':
continue
value = form.cleaned_data[key]
if key in associated_models and value:
value = associated_models[key].objects.get(pk=value)
dct[key] = value
person = self.get_current_object(request, storage)
if not person:
return self.render(request, storage, form)
for key in dct.keys():
if key.startswith('hidden_password'):
dct['password'] = dct.pop(key)
try:
account = models.IshtarUser.objects.get(person=person)
account.username = dct['username']
account.email = dct['email']
except ObjectDoesNotExist:
now = datetime.datetime.now()
account = models.IshtarUser(person=person, username=dct['username'],
email=dct['email'], first_name=person.surname,
last_name=person.name, is_staff=False, is_active=True,
is_superuser=False, last_login=now, date_joined=now)
if dct['password']:
account.set_password(dct['password'])
account.save()
if 'send_password' in dct and dct['send_password'] and \
settings.ADMINS:
site = Site.objects.get_current()
app_name = site and ("Ishtar - " + site.name) \
or "Ishtar"
context = Context({'login':dct['username'],
'password':dct['password'],
'app_name':app_name,
'site': site and site.domain or ""
})
t = loader.get_template('account_activation_email.txt')
msg = t.render(context)
subject = _(u"[%(app_name)s] Account creation/modification") % {
"app_name":app_name}
send_mail(subject, msg, settings.ADMINS[0][1],
[dct['email']], fail_silently=True)
res = render_to_response('wizard_done.html', {},
context_instance=RequestContext(request))
return res
def get_form(self, request, storage, step=None, data=None, files=None):
"""
Display the "Send email" field if necessary
"""
form = super(AccountWizard, self).get_form(request, storage, step, data,
files)
if not hasattr(form, 'is_hidden'):
return form
if self.session_get_value(request, storage,
'account-account_management', 'hidden_password'):
form.is_hidden = False
return form
class AccountForm(forms.Form):
form_label = _("Account")
associated_models = {'pk':models.Person}
currents = {'pk':models.Person}
pk = forms.IntegerField(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 \
password."))
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)
account_management_wizard = AccountWizard([
('selec-account_management', PersonFormSelection),
('account-account_management', AccountForm),
('final-account_management', FinalAccountForm)],
url_name='account_management',)
class TownForm(forms.Form):
form_label = _("Towns")
associated_models = {'town':models.Town}
# !FIXME hard_link, reverse_lazy doen't seem to work with formsets
town = forms.IntegerField(label=_(u"Town"), required=False,
widget=widgets.JQueryAutoComplete("/" + settings.URL_PATH + \
'autocomplete-town', associated_model=models.Town),
validators=[models.valid_id(models.Town)])
class TownFormSet(FormSet):
def clean(self):
"""Checks that no towns are duplicated."""
if any(self.errors):
return
towns = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
if not form.is_valid():
continue
if 'town' not in form.cleaned_data or not form.cleaned_data['town']:
continue
town = form.cleaned_data['town']
if town in towns:
raise forms.ValidationError, _("There are identical towns.")
towns.append(town)
TownFormSet = formset_factory(TownForm, can_delete=True, formset=TownFormSet)
TownFormSet.form_label = _("Towns")
class ParcelForm(forms.Form):
form_label = _("Parcels")
base_model = 'parcel'
associated_models = {'parcel':models.Parcel, 'town':models.Town}
town = forms.ChoiceField(label=_("Town"), choices=(), required=False,
validators=[models.valid_id(models.Town)])
section = forms.CharField(label=_(u"Section"), required=False,
validators=[validators.MaxLengthValidator(4)])
parcel_number = forms.CharField(label=_(u"Parcel number"), required=False,
validators=[validators.MaxLengthValidator(6)])
year = forms.IntegerField(label=_("Year"), required=False,
initial=lambda:datetime.datetime.now().year,
validators=[validators.MinValueValidator(1900),
validators.MaxValueValidator(2100)])
def __init__(self, *args, **kwargs):
towns = None
if 'data' in kwargs and 'TOWNS' in kwargs['data']:
towns = kwargs['data']['TOWNS']
# clean data if not "real" data
prefix_value = kwargs['prefix'] + '-town'
if not [k for k in kwargs['data'].keys()
if k.startswith(prefix_value) and kwargs['data'][k]]:
kwargs['data'] = None
if 'files' in kwargs:
kwargs.pop('files')
super(ParcelForm, self).__init__(*args, **kwargs)
if towns:
self.fields['town'].choices = [('', '--')] + towns
def clean(self):
"""Check required fields"""
if any(self.errors):
return
if not self.cleaned_data or DELETION_FIELD_NAME in self.cleaned_data \
and self.cleaned_data[DELETION_FIELD_NAME]:
return
for key in ('town', 'parcel_number', 'year'):
if not key in self.cleaned_data or not self.cleaned_data[key]:
raise forms.ValidationError(_(u"All fields are required"))
return self.cleaned_data
class ParcelFormSet(FormSet):
def clean(self):
"""Checks that no parcels are duplicated."""
return clean_duplicated(self, ('town', 'parcel_number', 'year'))
ParcelFormSet = formset_factory(ParcelForm, can_delete=True,
formset=ParcelFormSet)
ParcelFormSet.form_label = _("Parcels")
|