diff options
author | Étienne Loks <etienne.loks@peacefrogs.net> | 2011-06-07 23:59:36 +0200 |
---|---|---|
committer | Étienne Loks <etienne.loks@peacefrogs.net> | 2011-06-07 23:59:36 +0200 |
commit | 4bc7a3972eb4ff1bd2b013834c6e441e6fb01bf3 (patch) | |
tree | 5400d28a9c93d6a0e0b2fcf410fb04b36ea214f8 | |
parent | 68f31548d057d69683a876df609ee611a069c4f2 (diff) | |
download | Ishtar-4bc7a3972eb4ff1bd2b013834c6e441e6fb01bf3.tar.bz2 Ishtar-4bc7a3972eb4ff1bd2b013834c6e441e6fb01bf3.zip |
First work to modularize the application: administrative forms
-rw-r--r-- | ishtar/furnitures/forms.py | 185 | ||||
-rw-r--r-- | ishtar/furnitures/forms_administrative.py | 231 | ||||
-rw-r--r-- | ishtar/furnitures/forms_main.py | 22 | ||||
-rw-r--r-- | ishtar/furnitures/urls.py | 2 | ||||
-rw-r--r-- | ishtar/furnitures/views.py | 2 |
5 files changed, 255 insertions, 187 deletions
diff --git a/ishtar/furnitures/forms.py b/ishtar/furnitures/forms.py index bb6555547..7e55567db 100644 --- a/ishtar/furnitures/forms.py +++ b/ishtar/furnitures/forms.py @@ -640,191 +640,6 @@ def get_now(): value = datetime.datetime.now().strftime(format) return value -class PersonWizard(Wizard): - model = models.Person - -class PersonFormSelection(forms.Form): - form_label = _("Person") - 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?")) - -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 FileWizard(Wizard): model = models.File object_parcel_type = 'associated_file' diff --git a/ishtar/furnitures/forms_administrative.py b/ishtar/furnitures/forms_administrative.py new file mode 100644 index 000000000..c7bf47858 --- /dev/null +++ b/ishtar/furnitures/forms_administrative.py @@ -0,0 +1,231 @@ +#/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.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, reverse_lazy, name_validator + +class PersonWizard(Wizard): + model = models.Person + +class PersonFormSelection(forms.Form): + form_label = _("Person") + 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',) + + + diff --git a/ishtar/furnitures/forms_main.py b/ishtar/furnitures/forms_main.py new file mode 100644 index 000000000..d44ecfd87 --- /dev/null +++ b/ishtar/furnitures/forms_main.py @@ -0,0 +1,22 @@ +#/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. + +from forms_administrative import * +from forms import * + diff --git a/ishtar/furnitures/urls.py b/ishtar/furnitures/urls.py index e7e9ff85a..ee67882cc 100644 --- a/ishtar/furnitures/urls.py +++ b/ishtar/furnitures/urls.py @@ -21,7 +21,7 @@ from django.conf.urls.defaults import * from ishtar.urls import BASE_URL from menus import menu -import forms as ishtar_forms +import forms_main as ishtar_forms urlpatterns, actions = [], [] diff --git a/ishtar/furnitures/views.py b/ishtar/furnitures/views.py index 7dfe6d2dd..40e9aeaf0 100644 --- a/ishtar/furnitures/views.py +++ b/ishtar/furnitures/views.py @@ -48,7 +48,7 @@ if settings.XHTML2ODT_PATH: from xhtml2odt import xhtml2odt from menus import menu -import forms as ishtar_forms +import forms_main as ishtar_forms import models CSV_OPTIONS = {'delimiter':';', 'quotechar':'"', 'quoting':csv.QUOTE_ALL} |