diff options
Diffstat (limited to 'ishtar/furnitures/forms.py')
| -rw-r--r-- | ishtar/furnitures/forms.py | 159 | 
1 files changed, 130 insertions, 29 deletions
| diff --git a/ishtar/furnitures/forms.py b/ishtar/furnitures/forms.py index 536c1c037..f0b891961 100644 --- a/ishtar/furnitures/forms.py +++ b/ishtar/furnitures/forms.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#/usr/bin/env python  # -*- coding: utf-8 -*-  # Copyright (C) 2010  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet> @@ -33,6 +33,7 @@ from django.shortcuts import render_to_response  from django.template import Context, RequestContext  from django.db.models import Max  from django import forms +from django.core.mail import send_mail  from django.forms.formsets import formset_factory, BaseFormSet, \                                    DELETION_FIELD_NAME  from django.contrib.auth.models import User @@ -277,6 +278,29 @@ class Wizard(NamedUrlSessionFormWizard):                  pass          return super(Wizard, self).process_post_request(request, storage, *args,                                                          **kwargs) +    @classmethod +    def session_has_key(cls, request, storage, form_key, key=None): +        """ +        Check if the session has value of a specific form and (if provided) +        of a key +        """ +        test = storage.prefix in request.session \ +          and 'step_data' in request.session[storage.prefix] \ +          and form_key in request.session[storage.prefix]['step_data'] +        if not key or not test: +            return test +        key = key.startswith(form_key) and key or form_key + '-' + key +        return key in request.session[storage.prefix]['step_data'][form_key] + +    @classmethod +    def session_get_value(cls, request, storage, form_key, key): +        """ +        Get the value of a specific form +        """ +        if not cls.session_has_key(request, storage, form_key, key): +            return +        key = key.startswith(form_key) and key or form_key + '-' + key +        return request.session[storage.prefix]['step_data'][form_key][key]      def get_current_object(self, request, storage):          """ @@ -284,18 +308,12 @@ class Wizard(NamedUrlSessionFormWizard):          """          current_obj = None          main_form_key = 'selec-' + self.url_name -        pk = main_form_key + '-pk' -        if storage.prefix in request.session \ -           and 'step_data' in request.session[storage.prefix] \ -           and main_form_key in request.session[storage.prefix]['step_data'] \ -           and pk in request.session[storage.prefix]['step_data']\ -                                                    [main_form_key]: -            try: -                idx = int(request.session[storage.prefix]['step_data'] -                                                         [main_form_key][pk]) -                current_obj = self.model.objects.get(pk=idx) -            except(TypeError, ObjectDoesNotExist): -                pass +        try: +            idx = int(self.session_get_value(request, storage, main_form_key, +                                             'pk')) +            current_obj = self.model.objects.get(pk=idx) +        except(TypeError, ObjectDoesNotExist): +            pass          return current_obj      def get_form_initial(self, request, storage, step): @@ -406,7 +424,7 @@ person_creation_wizard = PersonWizard([                           url_name='person_creation',)  class AccountWizard(Wizard): -    model = User +    model = models.Person      def get_formated_datas(self, forms):          datas = super(AccountWizard, self).get_formated_datas(forms)          for form in forms: @@ -415,9 +433,75 @@ class AccountWizard(Wizard):              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: +            app_name = settings.APP_NAME and (" - " + settings.APP_NAME) or "" +            subject = u"[Ishtar%(app_name)s] Account creation/modification" % { +                                                           "app_name":app_name} +            msg = _(u"You can now log into Ishtar.\n\n" +                    u" * Login: %(login)s\n" +                    u" * Password: %(password)s" % {'login':dct['username'], +                                                    'password':dct['password']}) +            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 PersonFormSelection(forms.Form):      form_label = _("Person")      associated_models = {'pk':models.Person} @@ -429,6 +513,8 @@ class PersonFormSelection(forms.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, @@ -440,12 +526,23 @@ class AccountForm(forms.Form):                  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 " -"password do not match.")) +                                          u"password do not match."))          if not cleaned_data.get("pk"):              models.is_unique(User, 'username')(cleaned_data.get("username"))              if not password: @@ -453,10 +550,20 @@ class AccountForm(forms.Form):  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?")) + +    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', FinalForm)], +                        ('final-account_management', FinalAccountForm)],                           url_name='account_management',)  class FileWizard(Wizard): @@ -476,9 +583,7 @@ class FileWizard(Wizard):          form = self.get_form_list(request, storage)[step]          town_form_key = 'towns-' + self.url_name          if step.startswith('parcels-') and hasattr(form, 'management_form') \ -           and storage.prefix in request.session \ -           and 'step_data' in request.session[storage.prefix] \ -           and town_form_key in request.session[storage.prefix]['step_data']: +           and self.session_has_key(request, storage, town_form_key):              towns = []              qdict = request.session[storage.prefix]['step_data'][town_form_key]              for k in qdict.keys(): @@ -747,9 +852,7 @@ class OperationWizard(Wizard):          # put hidden year field          general_form_key = 'general-' + self.url_name          if not data and step.startswith('refs-') \ -           and storage.prefix in request.session \ -           and 'step_data' in request.session[storage.prefix] \ -           and general_form_key in request.session[storage.prefix]['step_data']: +           and self.session_has_key(request, storage, general_form_key):              prefix = 'refs-' + self.url_name              year = int(request.session[storage.prefix]['step_data']\                                    [general_form_key][general_form_key+"-year"]) @@ -758,9 +861,7 @@ class OperationWizard(Wizard):                                  Max('operation_code'))["operation_code__max"]              data[prefix+'-operation_code'] = max_val and (max_val + 1) or 1          if step.startswith('towns-') and hasattr(form, 'management_form') \ -           and storage.prefix in request.session \ -           and 'step_data' in request.session[storage.prefix] \ -           and general_form_key in request.session[storage.prefix]['step_data']: +           and self.session_has_key(request, storage, general_form_key):              towns = []              try:                  file_id = int(request.session[storage.prefix]['step_data']\ @@ -780,9 +881,9 @@ class OperationFormSelection(forms.Form):      associated_models = {'pk':models.Operation}      currents = {'pk':models.Operation}      pk = forms.IntegerField(label=_("Operation"), -         widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-operation'), -                                           associated_model=models.Operation), -         validators=[models.valid_id(models.Operation)]) +       widget=widgets.JQueryAutoComplete(reverse_lazy('autocomplete-operation'), +                                         associated_model=models.Operation), +       validators=[models.valid_id(models.Operation)])  class OperationFormGeneral(forms.Form): | 
