diff options
-rw-r--r-- | ishtar_common/forms_common.py | 118 | ||||
-rw-r--r-- | ishtar_common/urls.py | 12 | ||||
-rw-r--r-- | ishtar_common/views.py | 169 |
3 files changed, 170 insertions, 129 deletions
diff --git a/ishtar_common/forms_common.py b/ishtar_common/forms_common.py index d034f6ddf..e5f23e620 100644 --- a/ishtar_common/forms_common.py +++ b/ishtar_common/forms_common.py @@ -194,104 +194,6 @@ class PersonForm(forms.Form): new_item.save() return new_item -''' -person_search_wizard = SearchWizard([ - ('general-person_search', PersonFormSelection)], - url_name='person_search',) - - - -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} @@ -301,11 +203,11 @@ class AccountForm(forms.Form): 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)]) + 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) + 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']: @@ -327,8 +229,8 @@ class AccountForm(forms.Form): 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.")) + raise forms.ValidationError(_(u"You must provide a correct "\ + u"password.")) # check username unicity usernames = models.IshtarUser.objects.filter(username= cleaned_data.get('username')) @@ -347,13 +249,7 @@ class FinalAccountForm(forms.Form): 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") base_model = 'town' diff --git a/ishtar_common/urls.py b/ishtar_common/urls.py index 437a6bbb4..f6636255e 100644 --- a/ishtar_common/urls.py +++ b/ishtar_common/urls.py @@ -30,16 +30,14 @@ urlpatterns, actions = [], [] # forms urlpatterns = patterns('', # General - url(r'person_creation/(?P<step>.+)$', - views.person_creation_wizard, name='person_creation_step'), - url(r'person_creation/$', + url(r'person_creation/(?P<step>.+)?$', views.person_creation_wizard, name='person_creation'), + url(r'person_modification/(?P<step>.+)?$', + views.person_modification_wizard, name='person_modification'), + url(r'account_management/(?P<step>.+)?$', + views.account_management_wizard, name='account_management'), ) """ - url(r'person_modification/(?P<step>.+)$', - ishtar_forms.person_modification_wizard, name='person_modification'), - url(r'account_management/(?P<step>.+)$', - ishtar_forms.account_management_wizard, name='account_management'), # Archaelogical files url(r'file_search/(?P<step>.+)$', ishtar_forms.file_search_wizard, name='file_search'), diff --git a/ishtar_common/views.py b/ishtar_common/views.py index eecd1ebd4..fe464ade7 100644 --- a/ishtar_common/views.py +++ b/ishtar_common/views.py @@ -32,6 +32,7 @@ from tempfile import NamedTemporaryFile import ho.pisa as pisa from django.conf import settings +from django.contrib.auth import logout from django.contrib.formtools.wizard.views import NamedUrlWizardView from django.core import serializers from django.core.exceptions import ObjectDoesNotExist @@ -52,7 +53,8 @@ from menus import menu import forms_main as ishtar_forms from ishtar_common.forms import FinalForm -from ishtar_common.forms_common import PersonForm +from ishtar_common.forms_common import PersonForm, PersonFormSelection,\ + AccountForm, FinalAccountForm import models CSV_OPTIONS = {'delimiter':';', 'quotechar':'"', 'quoting':csv.QUOTE_ALL} @@ -63,11 +65,18 @@ def index(request): Main page """ dct = {} - return render_to_response('index.html', dct, + try: + return render_to_response('index.html', dct, + context_instance=RequestContext(request)) + except NoReverseMatch: + # probably rights exception (rights revoked) + logout(request) + return render_to_response('index.html', dct, context_instance=RequestContext(request)) class Wizard(NamedUrlWizardView): model = None + label = '' modification = None # True when the wizard modify an item storage_name = 'django.contrib.formtools.wizard.storage.session.SessionStorage' @@ -103,6 +112,7 @@ class Wizard(NamedUrlWizardView): def __init__(self, *args, **kwargs): """Check right for each step of the wizard""" + print "2" super(Wizard, self).__init__(*args, **kwargs) for form_key in self.form_list.keys()[:-1]: condition = True @@ -118,11 +128,20 @@ class Wizard(NamedUrlWizardView): cond = self._check_right(form_key, condition) self.condition_list[form_key] = cond""" + def get_prefix(self, *args, **kwargs): + """As the class name can interfere when reused prefix with the url_name + """ + print "3" + return self.url_name + super(Wizard, self).get_prefix(*args, + **kwargs) + def get_wizard_name(self): """As the class name can interfere when reused, use the url_name""" + print "4" return self.url_name def get_template_names(self): + print "5" templates = ['ishtar/wizard/default_wizard.html'] current_step = self.steps.current if current_step == self.steps.last: @@ -131,28 +150,36 @@ class Wizard(NamedUrlWizardView): def get_context_data(self, form, **kwargs): """Add previous, next and current steps to manage the wizard path""" + print "6" context = super(Wizard, self).get_context_data(form) + self.request.session['CURRENT_ACTION'] = self.get_wizard_name() step = self.steps.first current_step = self.steps.current - context.update({'current_step':self.form_list[current_step]}) + context.update({'current_step':self.form_list[current_step], + 'wizard_label':self.label}) if step == current_step: return context previous_steps, next_steps, previous_step_counter = [], [], 0 while step: - if step == current_step: + if step == current_step \ + or (previous_steps and + previous_steps[-1] == self.form_list[step]): break previous_steps.append(self.form_list[step]) - step = self.steps.next previous_step_counter += 1 + if previous_step_counter >= len(self.steps): + break + step = self.steps.all[previous_step_counter] context.update({'previous_steps':previous_steps, 'previous_step_counter':previous_step_counter}) + storage = self.storage # if modification: show the next steps if self.modification: next_step = step while next_step: # check if the form is initialized otherwise initialize it if not storage.get_step_data(next_step): - values = self.get_form_initial(request, storage, next_step) + values = self.get_form_initial(next_step) prefixed_values = {} if not isinstance(values, list): for key in values: @@ -167,7 +194,7 @@ class Wizard(NamedUrlWizardView): storage.set_step_data(next_step, prefixed_values) if step != next_step: # if not current step next_steps.append(self.form_list[next_step]) - next_step = self.get_next_step(request, storage, next_step) + next_step = self.get_next_step(next_step) context.update({'next_steps':next_steps}) # not last step: validation if current_step != self.steps.last: @@ -189,6 +216,7 @@ class Wizard(NamedUrlWizardView): def get_formated_datas(self, forms): """Get the data to present in the last page""" + print "7" datas = [] for form in forms: form_datas = [] @@ -253,11 +281,13 @@ class Wizard(NamedUrlWizardView): return datas def get_extra_model(self, dct, form_list): + print "8" dct['history_modifier'] = self.request.user return dct def done(self, form_list, return_object=False, **kwargs): """Save to the model""" + print "9" dct, m2m, whole_associated_models = {}, [], [] for form in form_list: if not form.is_valid(): @@ -327,14 +357,17 @@ class Wizard(NamedUrlWizardView): def get_saved_model(self): """Permit a distinguo when saved model is not the base selected model""" + print "10" return self.model def get_current_saved_object(self): """Permit a distinguo when saved model is not the base selected model""" + print "11" return self.get_current_object() def save_model(self, dct, m2m, whole_associated_models, form_list, return_object): + print "12" dct = self.get_extra_model(dct, form_list) obj = self.get_current_saved_object() # manage dependant items @@ -436,6 +469,7 @@ class Wizard(NamedUrlWizardView): def get_deleted(self, keys): """Get the deleted and non-deleted items in formsets""" + print "13" not_to_delete, to_delete = set(), set() for key in keys: items = key.split('-') @@ -456,6 +490,7 @@ class Wizard(NamedUrlWizardView): def get_form(self, step=None, data=None, files=None): """Manage formset""" + print "14" request = self.request storage = self.storage if data: @@ -504,6 +539,7 @@ class Wizard(NamedUrlWizardView): - modify or delete button in formset: next step = current step - validate and end: nextstep = last step """ + print "15" request = self.request if request.POST.has_key('formset_modify') \ and request.POST['formset_modify'] \ @@ -522,6 +558,7 @@ class Wizard(NamedUrlWizardView): def post(self, *args, **kwargs): """Convert numerical step number to step name""" + print "16" request = self.request post_data = request.POST.copy() if request.POST.has_key('form_prev_step'): @@ -539,6 +576,7 @@ class Wizard(NamedUrlWizardView): """Check if the session has value of a specific form and (if provided) of a key """ + print "17" test = storage.prefix in request.session \ and 'step_data' in request.session[storage.prefix] \ and form_key in request.session[storage.prefix]['step_data'] @@ -552,6 +590,7 @@ class Wizard(NamedUrlWizardView): @classmethod def session_get_value(cls, request, storage, form_key, key, multi=False): """Get the value of a specific form""" + print "18" if not cls.session_has_key(request, storage, form_key, key, multi): return if not multi: @@ -567,25 +606,32 @@ class Wizard(NamedUrlWizardView): def get_current_object(self): """Get the current object for an instancied wizard""" + print "19" current_obj = None main_form_key = 'selec-' + self.url_name try: - idx = int(self.session_get_value(self.request, self.storage, - main_form_key, 'pk')) + idx = self.session_get_value(self.request, self.storage, + main_form_key, 'pk') + if type(idx) in (tuple, list): + idx = idx[0] + idx = int(idx) current_obj = self.model.objects.get(pk=idx) except(TypeError, ValueError, ObjectDoesNotExist): pass return current_obj def get_form_initial(self, step): + print "20" current_obj = self.get_current_object() current_step = self.steps.current + request = self.request if step.startswith('selec-') and step in self.form_list \ and 'pk' in self.form_list[step].associated_models: model_name = self.form_list[step].associated_models['pk' ].__name__.lower() if step == current_step: - self.reset_wizard(request, storage) + #self.reset_wizard(request, storage) + self.storage.reset() val = model_name in request.session and request.session[model_name] if val: return {'pk':val} @@ -606,6 +652,7 @@ class Wizard(NamedUrlWizardView): def get_instanced_init(self, obj, step=None): """Get initial data from an init""" + print "21" current_step = step or self.steps.current c_form = self.form_list[current_step] # make the current object the default item for the session @@ -672,8 +719,108 @@ class PersonWizard(Wizard): person_creation_wizard = PersonWizard.as_view([ ('identity-person_creation', PersonForm), ('final-person_creation', FinalForm)], - url_name='person_creation_step',) + label=_(u"Person creation"), + url_name='person_creation') + +class PersonModifWizard(PersonWizard): + modification = True + +person_modification_wizard = PersonModifWizard.as_view([ + ('selec-person_modification', PersonFormSelection), + ('identity-person_modification', PersonForm), + ('final-person_modification', FinalForm)], + label=_(u"Person modification"), + 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, form_list, **kwargs): + """ + Save the account + """ + dct = {} + for form in form_list: + if not form.is_valid(): + return self.render(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() + if not person: + return self.render(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(self.request)) + return res + + def get_form(self, step=None, data=None, files=None): + """ + Display the "Send email" field if necessary + """ + form = super(AccountWizard, self).get_form(step, data, files) + if not hasattr(form, 'is_hidden'): + return form + if self.session_get_value(self.request, self.storage, + 'account-account_management', 'hidden_password'): + form.is_hidden = False + return form +account_management_wizard = AccountWizard.as_view([ + ('selec-account_management', PersonFormSelection), + ('account-account_management', AccountForm), + ('final-account_management', FinalAccountForm)], + label=_(u"Account management"), + url_name='account_management',) def update_current_item(request): if not request.is_ajax() and not request.method == 'POST': |