From 373a9d9531f2cb7ef954f7af14baaea33b74bdff Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Fri, 17 Nov 2017 13:31:20 +0100 Subject: Custom forms: admin form --- ishtar_common/forms.py | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'ishtar_common/forms.py') diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index 5c3de7b77..d0c2bb035 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -298,6 +298,11 @@ class ManageOldType(object): self.fields[field_name].help_text = model.get_help() +class CustomForm(object): + form_admin_name = "" + form_slug = "" + + class DocumentGenerationForm(forms.Form): """ Form to generate document by choosing the template -- cgit v1.2.3 From a9d9b977778068d2609342d2749123618108e9d7 Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Sun, 19 Nov 2017 20:08:16 +0100 Subject: Custom forms: admin forms --- ishtar_common/admin.py | 87 +++++++++++++++++++++++++++++++++++++++++-------- ishtar_common/forms.py | 27 +++++++++++++++ ishtar_common/models.py | 48 +++++++++++++++++++++++++-- ishtar_common/utils.py | 6 ++-- 4 files changed, 151 insertions(+), 17 deletions(-) (limited to 'ishtar_common/forms.py') diff --git a/ishtar_common/admin.py b/ishtar_common/admin.py index 8045bff13..7c21fa4be 100644 --- a/ishtar_common/admin.py +++ b/ishtar_common/admin.py @@ -32,6 +32,7 @@ from django.contrib.sites.admin import SiteAdmin from django.contrib.sites.models import Site from django.contrib.gis.forms import PointField, OSMWidget, MultiPolygonField from django.core.cache import cache +from django.forms import BaseInlineFormSet from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render from django.template.defaultfilters import slugify @@ -91,6 +92,7 @@ def gen_import_generic(self, request, queryset): request.POST.getlist(admin.ACTION_CHECKBOX_NAME)}) return render(request, 'admin/import_from_csv.html', {'csv_form': form}) + gen_import_generic.short_description = "Import from a CSV file" @@ -166,6 +168,7 @@ class IshtarSiteProfileAdmin(admin.ModelAdmin): 'find', 'warehouse', 'mapping', 'preservation') model = models.IshtarSiteProfile + admin_site.register(models.IshtarSiteProfile, IshtarSiteProfileAdmin) @@ -173,6 +176,7 @@ class DepartmentAdmin(admin.ModelAdmin): list_display = ('number', 'label',) model = models.Department + admin_site.register(models.Department, DepartmentAdmin) @@ -183,6 +187,7 @@ class OrganizationAdmin(HistorizedObjectAdmin): exclude = ('merge_key', 'merge_exclusion', 'merge_candidate', ) model = models.Organization + admin_site.register(models.Organization, OrganizationAdmin) @@ -194,6 +199,7 @@ class PersonAdmin(HistorizedObjectAdmin): form = make_ajax_form(models.Person, {'attached_to': 'organization'}) model = models.Person + admin_site.register(models.Person, PersonAdmin) @@ -251,6 +257,7 @@ class AuthorAdmin(admin.ModelAdmin): model = models.Author form = make_ajax_form(models.Author, {'person': 'person'}) + admin_site.register(models.Author, AuthorAdmin) @@ -259,11 +266,14 @@ class PersonTypeAdmin(admin.ModelAdmin): model = models.PersonType filter_vertical = ('groups',) + admin_site.register(models.PersonType, PersonTypeAdmin) class GlobalVarAdmin(admin.ModelAdmin): list_display = ['slug', 'description', 'value'] + + admin_site.register(models.GlobalVar, GlobalVarAdmin) @@ -290,16 +300,22 @@ class ImporterDefaultAdmin(admin.ModelAdmin): list_display = ('importer_type', 'target') model = models.ImporterDefault inlines = (ImporterDefaultValuesInline,) + + admin_site.register(models.ImporterDefault, ImporterDefaultAdmin) class ImporterTypeAdmin(admin.ModelAdmin): list_display = ('name', 'associated_models', 'available') + + admin_site.register(models.ImporterType, ImporterTypeAdmin) class RegexpAdmin(admin.ModelAdmin): list_display = ('name', 'description', "regexp") + + admin_site.register(models.Regexp, RegexpAdmin) @@ -327,6 +343,8 @@ class ImporterColumnAdmin(admin.ModelAdmin): 'targets_lbl', 'duplicate_fields_lbl', 'required') list_filter = ('importer_type',) inlines = (ImportTargetInline, ImporterDuplicateFieldInline) + + admin_site.register(models.ImporterColumn, ImporterColumnAdmin) @@ -392,6 +410,8 @@ admin_site.register(models.SpatialReferenceSystem, SpatialReferenceSystemAdmin) class ItemKeyAdmin(admin.ModelAdmin): list_display = ('content_type', 'key', 'content_object', 'importer') search_fields = ('key', ) + + admin_site.register(models.ItemKey, ItemKeyAdmin) @@ -449,18 +469,10 @@ def get_choices_form(): cache_key, value = get_cache(models.CustomForm, ['associated-forms']) if value: return value - forms = set() - for app_form in ISHTAR_FORMS: - for form in dir(app_form): - if 'Form' not in form: - # not very clean... but do not treat inappropriate items - continue - form = getattr(app_form, form) - if not issubclass(form, common_forms.CustomForm)\ - or not getattr(form, 'form_slug', None): - continue - forms.add((form.form_slug, form.form_admin_name)) - forms = list(forms) + forms = [] + for slug in models.CustomForm.register(): + forms.append((slug, models.CustomForm._register[slug].form_admin_name)) + forms = sorted(forms, key=lambda x: x[1]) cache.set(cache_key, forms, settings.CACHE_TIMEOUT) return forms @@ -474,9 +486,57 @@ class CustomFormForm(forms.ModelForm): label=_(u"Users")) +class ExcludeFieldFormset(BaseInlineFormSet): + def get_form_kwargs(self, index): + kwargs = super(ExcludeFieldFormset, self).get_form_kwargs(index) + if not self.instance or not self.instance.pk: + return kwargs + form = self.instance.get_form_class() + if not form: + kwargs['choices'] = [] + return kwargs + kwargs['choices'] = [('', '--')] + form.get_custom_fields() + return kwargs + + +class ExcludeFieldForm(forms.ModelForm): + class Meta: + model = models.ExcludedField + exclude = [] + field = forms.ChoiceField(label=_(u"Field")) + + def __init__(self, *args, **kwargs): + choices = kwargs.pop('choices') + super(ExcludeFieldForm, self).__init__(*args, **kwargs) + self.fields['field'].choices = choices + + +class ExcludeFieldInline(admin.TabularInline): + model = models.ExcludedField + extra = 2 + form = ExcludeFieldForm + formset = ExcludeFieldFormset + + class CustomFormAdmin(admin.ModelAdmin): - list_display = ['name', 'form', 'available'] + list_display = ['name', 'form', 'available', 'apply_to_all', + 'users_lbl', 'user_types_lbl'] + fields = ('name', 'form', 'available', 'apply_to_all', 'users', + 'user_types') form = CustomFormForm + inlines = [ExcludeFieldInline] + + def get_inline_instances(self, request, obj=None): + # no inline on creation + if not obj: + return [] + return super(CustomFormAdmin, self).get_inline_instances(request, + obj=obj) + + def get_readonly_fields(self, request, obj=None): + if obj: + return ('form',) + return [] admin_site.register(models.CustomForm, CustomFormAdmin) @@ -515,6 +575,7 @@ class AdministrationTaskAdmin(admin.ModelAdmin): return ("script", ) + self.readonly_fields return self.readonly_fields + admin_site.register(models.AdministrationTask, AdministrationTaskAdmin) diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index d0c2bb035..0f1fa20f8 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -302,6 +302,33 @@ class CustomForm(object): form_admin_name = "" form_slug = "" + def __init__(self, *args, **kwargs): + super(CustomForm, self).__init__(*args, **kwargs) + # todo: filter by user / group... + q = models.CustomForm.objects.filter(form=self.form_slug, + available=True, apply_to_all=True) + if not q.count(): + return + # todo: prevent multiple result in database + form = q.all()[0] + for excluded in form.excluded_fields.all(): + # could have be filtered previously + if excluded.field in self.fields: + self.fields.pop(excluded.field) + + @classmethod + def get_custom_fields(cls): + fields = cls.base_fields + customs = [] + for key in fields: + field = fields[key] + # cannot customize display of required and hidden field + # field with no label are also rejected + if field.required or field.widget.is_hidden or not field.label: + continue + customs.append((key, field.label)) + return sorted(customs, key=lambda x: x[1]) + class DocumentGenerationForm(forms.Form): """ diff --git a/ishtar_common/models.py b/ishtar_common/models.py index a5a3d96c1..c888e87fd 100644 --- a/ishtar_common/models.py +++ b/ishtar_common/models.py @@ -1647,14 +1647,58 @@ class CustomForm(models.Model): verbose_name_plural = _(u"Custom forms") ordering = ['name', 'form'] + def users_lbl(self): + users = [unicode(user) for user in self.users.all()] + return " ; ".join(users) + + users_lbl.short_description = _(u"Users") + + def user_types_lbl(self): + user_types = [unicode(u) for u in self.user_types.all()] + return " ; ".join(user_types) + + user_types_lbl.short_description = _(u"User types") + + @classmethod + def register(cls): + if hasattr(cls, '_register'): + return cls._register + cache_key, value = get_cache(cls.__class__, ['dct-forms'], + app_label='ishtar_common') + if value: + cls._register = value + return cls._register + cls._register = {} + # ideally should be improved but only used in admin + from ishtar_common.admin import ISHTAR_FORMS + from ishtar_common.forms import CustomForm + + for app_form in ISHTAR_FORMS: + for form in dir(app_form): + if 'Form' not in form: + # not very clean... but do not treat inappropriate items + continue + form = getattr(app_form, form) + if not issubclass(form, CustomForm) \ + or not getattr(form, 'form_slug', None): + continue + cls._register[form.form_slug] = form + return cls._register + + def get_form_class(self): + register = self.register() + if self.form not in self._register: + return + return register[self.form] + class ExcludedField(models.Model): custom_form = models.ForeignKey(CustomForm, related_name='excluded_fields') field = models.CharField(_(u"Field"), max_length=250) class Meta: - verbose_name = _(u"Custom form - excluded field") - verbose_name_plural = _(u"Custom form - excluded fields") + verbose_name = _(u"Excluded field") + verbose_name_plural = _(u"Excluded fields") class GlobalVar(models.Model, Cached): diff --git a/ishtar_common/utils.py b/ishtar_common/utils.py index 5d9e85c60..ae178a752 100644 --- a/ishtar_common/utils.py +++ b/ishtar_common/utils.py @@ -51,9 +51,11 @@ def get_current_year(): return datetime.datetime.now().year -def get_cache(cls, extra_args=[]): +def get_cache(cls, extra_args=tuple(), app_label=None): + if not app_label: + app_label = cls._meta.app_label cache_key = u"{}-{}-{}".format( - settings.PROJECT_SLUG, cls._meta.app_label, cls.__name__) + settings.PROJECT_SLUG, app_label, cls.__name__) for arg in extra_args: if not arg: cache_key += '-0' -- cgit v1.2.3 From 9309d89a48cee876ef17213924b2cc0b026677f9 Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Mon, 20 Nov 2017 15:17:42 +0100 Subject: Custom forms: filter by user and by groups - tests --- archaeological_operations/tests.py | 82 +++++++++++++++++++++++++++++++++++++- ishtar_common/forms.py | 43 +++++++++++++++----- ishtar_common/tests.py | 70 ++++++++++++++++++-------------- 3 files changed, 154 insertions(+), 41 deletions(-) (limited to 'ishtar_common/forms.py') diff --git a/archaeological_operations/tests.py b/archaeological_operations/tests.py index ec7ae44c5..9f07aff45 100644 --- a/archaeological_operations/tests.py +++ b/archaeological_operations/tests.py @@ -40,7 +40,7 @@ from ishtar_common.models import OrganizationType, Organization, ItemKey, \ ImporterType, IshtarUser, TargetKey, ImporterModel, IshtarSiteProfile, \ Town, ImporterColumn, Person, Author, SourceType, AuthorType, \ DocumentTemplate, PersonType, TargetKeyGroup, JsonDataField, \ - JsonDataSection, ImportTarget, FormaterType + JsonDataSection, ImportTarget, FormaterType, CustomForm, ExcludedField from archaeological_files.models import File, FileType from archaeological_context_records.models import Unit @@ -1142,6 +1142,86 @@ class OperationTest(TestCase, OperationInitTest): self.assertNotIn(u"Marmotte".encode('utf-8'), response.content) +class CustomFormTest(TestCase, OperationInitTest): + fixtures = FILE_FIXTURES + + def setUp(self): + IshtarSiteProfile.objects.get_or_create( + slug='default', active=True) + self.username, self.password, self.user = create_superuser() + self.alt_username, self.alt_password, self.alt_user = create_user() + self.alt_user.user_permissions.add(Permission.objects.get( + codename='view_own_operation')) + self.orgas = self.create_orgas(self.user) + self.operations = self.create_operation(self.user, self.orgas[0]) + self.operations += self.create_operation(self.alt_user, self.orgas[0]) + self.item = self.operations[0] + + def test_filters(self): + c = Client() + c.login(username=self.username, password=self.password) + + cls_wiz = OperationWizardModifTest + url = reverse(cls_wiz.url_name) + # first wizard step + step = 'selec-operation_modification' + cls_wiz.wizard_post(c, url, step, {'pk': self.operations[0].pk}) + + step = 'general-operation_modification' + data = { + '{}{}-current_step'.format(cls_wiz.url_name, + cls_wiz.wizard_name): [step], + } + key_in_charge = "in_charge" + response = c.post(url, data) + self.assertIn( + key_in_charge, response.content, + msg="filter all - 'in charge' field not found on the modification " + "wizard") + f = CustomForm.objects.create(name="Test", form="operation-general", + available=True, apply_to_all=True) + ExcludedField.objects.create(custom_form=f, field="in_charge") + + response = c.post(url, data) + self.assertNotIn( + key_in_charge, response.content, + msg="filter all - 'in charge' field found on the modification " + "wizard. It should have been filtered.") + + # user type form prevail on "all" + f_scientist = CustomForm.objects.create( + name="Test", form="operation-general", available=True) + tpe = PersonType.objects.get(txt_idx='head_scientist') + key_address = "address" + f_scientist.user_types.add(tpe) + self.user.ishtaruser.person.person_types.add(tpe) + ExcludedField.objects.create(custom_form=f_scientist, field="address") + response = c.post(url, data) + self.assertIn( + key_in_charge, response.content, + msg="filter user type - 'in charge' field not found on the " + "modification wizard. It should not have been filtered.") + self.assertNotIn( + key_address, response.content, + msg="filter user type - 'address' field found on the " + "modification wizard. It should have been filtered.") + + # user prevail on "all" and "user_types" + f_user = CustomForm.objects.create( + name="Test", form="operation-general", available=True) + f_user.users.add(self.user.ishtaruser) + self.user.ishtaruser.person.person_types.add(tpe) + response = c.post(url, data) + self.assertIn( + key_in_charge, response.content, + msg="filter user - 'in charge' field not found on the modification " + "wizard. It should not have been filtered.") + self.assertIn( + key_address, response.content, + msg="filter user - 'address' field not found on the modification " + "wizard. It should not have been filtered.") + + class OperationSearchTest(TestCase, OperationInitTest): fixtures = FILE_FIXTURES diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index 0f1fa20f8..683726e67 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -301,20 +301,41 @@ class ManageOldType(object): class CustomForm(object): form_admin_name = "" form_slug = "" + need_user_for_initialization = True def __init__(self, *args, **kwargs): + current_user = None + if 'user' in kwargs: + try: + current_user = kwargs.pop('user').ishtaruser + except AttributeError: + pass super(CustomForm, self).__init__(*args, **kwargs) - # todo: filter by user / group... - q = models.CustomForm.objects.filter(form=self.form_slug, - available=True, apply_to_all=True) - if not q.count(): - return - # todo: prevent multiple result in database - form = q.all()[0] - for excluded in form.excluded_fields.all(): - # could have be filtered previously - if excluded.field in self.fields: - self.fields.pop(excluded.field) + base_q = {"form": self.form_slug, 'available': True} + # order is important : try for user, user type then all + query_dicts = [] + if current_user: + dct = base_q.copy() + dct.update({'users__pk': current_user.pk}) + query_dicts = [dct] + for user_type in current_user.person.person_types.all(): + dct = base_q.copy() + dct.update({'user_types__pk': user_type.pk}), + query_dicts.append(dct) + dct = base_q.copy() + dct.update({'apply_to_all': True}) + query_dicts.append(dct) + for query_dict in query_dicts: + q = models.CustomForm.objects.filter(**query_dict) + if not q.count(): + continue + # todo: prevent multiple result in database + form = q.all()[0] + for excluded in form.excluded_fields.all(): + # could have be filtered previously + if excluded.field in self.fields: + self.fields.pop(excluded.field) + break @classmethod def get_custom_fields(cls): diff --git a/ishtar_common/tests.py b/ishtar_common/tests.py index 63d80d5ab..016596772 100644 --- a/ishtar_common/tests.py +++ b/ishtar_common/tests.py @@ -288,6 +288,38 @@ class WizardTest(object): raise ValidationError(u"Errors: {} on {}.".format( u" ".join(errors), current_step)) + @classmethod + def wizard_post(cls, client, url, current_step, form_data=None, + follow=True): + if not url: + url = reverse(cls.url_name) + data = { + '{}{}-current_step'.format(cls.url_name, + cls.wizard_name): [current_step], + } + if not form_data: + form_data = [] + + # reconstruct a POST request + if type(form_data) in (list, tuple): # is a formset + for d_idx, item in enumerate(form_data): + for k in item: + data['{}-{}-{}'.format( + current_step, d_idx, k)] = item[k] + else: + for k in form_data: + data['{}-{}'.format(current_step, k)] = form_data[k] + + try: + response = client.post(url, data, follow=follow) + except ValidationError as e: + msg = u"Errors: {} on {}. On \"ManagementForm data is " \ + u"missing or...\" error verify the wizard_name or " \ + u"step name".format(u" - ".join(e.messages), + current_step) + raise ValidationError(msg) + return response + def test_wizard(self): if self.pass_test(): return @@ -301,35 +333,14 @@ class WizardTest(object): current_step, current_form = step if current_step in ignored: continue - data = { - '{}{}-current_step'.format(self.url_name, - self.wizard_name): - [current_step], - } - - # reconstruct a POST request - if current_step in form_data: - d = form_data[current_step] - if type(d) in (list, tuple): # is a formset - for d_idx, item in enumerate(d): - for k in item: - data['{}-{}-{}'.format( - current_step, d_idx, k)] = item[k] - else: - for k in d: - data['{}-{}'.format(current_step, k)] = d[k] - next_form_is_checked = len(self.steps) > idx + 1 and \ - self.steps[idx + 1][0] not in ignored - try: - response = self.client.post( - url, data, follow=not next_form_is_checked) - except ValidationError as e: - msg = u"Errors: {} on {}. On \"ManagementForm data is " \ - u"missing or...\" error verify the wizard_name or " \ - u"step name".format(u" - ".join(e.messages), - current_step) - raise ValidationError(msg) + self.steps[idx + 1][0] not in ignored + data = [] + if current_step in form_data: + data = form_data[current_step] + response = self.wizard_post( + self.client, url, current_step, data, + not next_form_is_checked) self.check_response(response, current_step) if next_form_is_checked: next_form = self.steps[idx + 1][0] @@ -402,7 +413,8 @@ class AdminGenTypeTest(TestCase): gen_models = [ models.OrganizationType, models.PersonType, models.TitleType, models.AuthorType, models.SourceType, models.OperationType, - models.SpatialReferenceSystem, models.Format, models.SupportType] + models.SpatialReferenceSystem, models.Format, models.SupportType, + ] models_with_data = gen_models + [models.ImporterModel] models = models_with_data module_name = 'ishtar_common' -- cgit v1.2.3 From c410be9b3c3ba193ee8c233cc6a50d065d4090fd Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Tue, 21 Nov 2017 10:46:58 +0100 Subject: Custom forms: disable completly a form --- archaeological_operations/forms.py | 7 ++- archaeological_operations/tests.py | 23 +++++++++ archaeological_operations/wizards.py | 6 ++- ishtar_common/admin.py | 4 +- ishtar_common/forms.py | 21 +++++++-- .../migrations/0024_custom_form_enabled.py | 24 ++++++++++ ishtar_common/models.py | 4 ++ ishtar_common/utils.py | 19 ++++++++ ishtar_common/wizards.py | 55 +++++++++++++--------- 9 files changed, 132 insertions(+), 31 deletions(-) create mode 100644 ishtar_common/migrations/0024_custom_form_enabled.py (limited to 'ishtar_common/forms.py') diff --git a/archaeological_operations/forms.py b/archaeological_operations/forms.py index 61be371d1..47fe746f5 100644 --- a/archaeological_operations/forms.py +++ b/archaeological_operations/forms.py @@ -997,8 +997,10 @@ OperationFormModifGeneral.associated_models = \ OperationFormModifGeneral.associated_models['associated_file'] = File -class CollaboratorForm(forms.Form): +class CollaboratorForm(CustomForm, forms.Form): form_label = _(u"Collaborators") + form_admin_name = _(u"Operation - Collaborators") + form_slug = "operation-collaborators" base_models = ['collaborator'] associated_models = {'collaborator': Person, } collaborator = widgets.Select2MultipleField( @@ -1006,7 +1008,8 @@ class CollaboratorForm(forms.Form): def __init__(self, *args, **kwargs): super(CollaboratorForm, self).__init__(*args, **kwargs) - self.fields['collaborator'].widget.attrs['full-width'] = True + if 'collaborator' in self.fields: + self.fields['collaborator'].widget.attrs['full-width'] = True class OperationFormPreventive(forms.Form): diff --git a/archaeological_operations/tests.py b/archaeological_operations/tests.py index 9f07aff45..af6199774 100644 --- a/archaeological_operations/tests.py +++ b/archaeological_operations/tests.py @@ -1221,6 +1221,29 @@ class CustomFormTest(TestCase, OperationInitTest): msg="filter user - 'address' field not found on the modification " "wizard. It should not have been filtered.") + def test_enabled(self): + c = Client() + c.login(username=self.username, password=self.password) + + cls_wiz = OperationWizardModifTest + url = reverse(cls_wiz.url_name) + # first wizard step + step = 'selec-operation_modification' + cls_wiz.wizard_post(c, url, step, {'pk': self.operations[0].pk}) + + step = 'collaborators-operation_modification' + data = { + '{}{}-current_step'.format(cls_wiz.url_name, + cls_wiz.wizard_name): [step], + } + response = c.post(url, data) + self.assertNotEqual(response.status_code, 404) + CustomForm.objects.create( + name="Test2", form="operation-collaborators", available=True, + apply_to_all=True, enabled=False) + response = c.post(url, data) + self.assertEqual(response.status_code, 404) + class OperationSearchTest(TestCase, OperationInitTest): fixtures = FILE_FIXTURES diff --git a/archaeological_operations/wizards.py b/archaeological_operations/wizards.py index fffe34ca7..24c1af45b 100644 --- a/archaeological_operations/wizards.py +++ b/archaeological_operations/wizards.py @@ -23,6 +23,7 @@ from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.db.models import Max +from django.http import Http404 from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ @@ -149,7 +150,10 @@ class OperationWizard(Wizard): data = {} if not step: step = self.steps.current - form = self.get_form_list()[step] + try: + form = self.get_form_list()[step] + except KeyError: + raise Http404() # manage the dynamic choice of towns if step.startswith('towns') and hasattr(form, 'management_form'): data['TOWNS'] = self.get_towns() diff --git a/ishtar_common/admin.py b/ishtar_common/admin.py index 7c21fa4be..189a02c05 100644 --- a/ishtar_common/admin.py +++ b/ishtar_common/admin.py @@ -519,9 +519,9 @@ class ExcludeFieldInline(admin.TabularInline): class CustomFormAdmin(admin.ModelAdmin): - list_display = ['name', 'form', 'available', 'apply_to_all', + list_display = ['name', 'form', 'available', 'enabled', 'apply_to_all', 'users_lbl', 'user_types_lbl'] - fields = ('name', 'form', 'available', 'apply_to_all', 'users', + fields = ('name', 'form', 'available', 'enabled', 'apply_to_all', 'users', 'user_types') form = CustomFormForm inlines = [ExcludeFieldInline] diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index 683726e67..da6a1c051 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -34,7 +34,7 @@ from django.utils.translation import ugettext_lazy as _ import models import widgets -from wizards import MultiValueDict +from ishtar_common.utils import MultiValueDict # from formwizard.forms import NamedUrlSessionFormWizard @@ -311,7 +311,17 @@ class CustomForm(object): except AttributeError: pass super(CustomForm, self).__init__(*args, **kwargs) - base_q = {"form": self.form_slug, 'available': True} + available, excluded = self.check_availability_and_excluded_fields( + current_user) + for exc in excluded: + if exc in self.fields: + self.fields.pop(exc) + + @classmethod + def check_availability_and_excluded_fields(cls, current_user): + if not current_user: + return True, [] + base_q = {"form": cls.form_slug, 'available': True} # order is important : try for user, user type then all query_dicts = [] if current_user: @@ -325,17 +335,20 @@ class CustomForm(object): dct = base_q.copy() dct.update({'apply_to_all': True}) query_dicts.append(dct) + excluded_lst = [] for query_dict in query_dicts: q = models.CustomForm.objects.filter(**query_dict) if not q.count(): continue # todo: prevent multiple result in database form = q.all()[0] + if not form.enabled: + return False, [] for excluded in form.excluded_fields.all(): # could have be filtered previously - if excluded.field in self.fields: - self.fields.pop(excluded.field) + excluded_lst.append(excluded.field) break + return True, excluded_lst @classmethod def get_custom_fields(cls): diff --git a/ishtar_common/migrations/0024_custom_form_enabled.py b/ishtar_common/migrations/0024_custom_form_enabled.py new file mode 100644 index 000000000..92fd32f6e --- /dev/null +++ b/ishtar_common/migrations/0024_custom_form_enabled.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11 on 2017-11-21 09:55 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('ishtar_common', '0023_excludedfield'), + ] + + operations = [ + migrations.AlterModelOptions( + name='excludedfield', + options={'verbose_name': 'Excluded field', 'verbose_name_plural': 'Excluded fields'}, + ), + migrations.AddField( + model_name='customform', + name='enabled', + field=models.BooleanField(default=True, help_text='Disable with caution: disabling a form with mandatory fields may lead to database errors.', verbose_name='Enable this form'), + ), + ] diff --git a/ishtar_common/models.py b/ishtar_common/models.py index c888e87fd..b0751f661 100644 --- a/ishtar_common/models.py +++ b/ishtar_common/models.py @@ -1635,6 +1635,10 @@ class CustomForm(models.Model): name = models.CharField(_(u"Name"), max_length=250) form = models.CharField(_(u"Form"), max_length=250) available = models.BooleanField(_(u"Available"), default=True) + enabled = models.BooleanField( + _(u"Enable this form"), default=True, + help_text=_(u"Disable with caution: disabling a form with mandatory " + u"fields may lead to database errors.")) apply_to_all = models.BooleanField( _(u"Apply to all"), default=False, help_text=_(u"Apply this form to all users. If set to True, selecting " diff --git a/ishtar_common/utils.py b/ishtar_common/utils.py index ae178a752..cc01f23e7 100644 --- a/ishtar_common/utils.py +++ b/ishtar_common/utils.py @@ -28,6 +28,7 @@ from django.conf import settings from django.contrib.gis.geos import GEOSGeometry from django.core.cache import cache from django.core.urlresolvers import reverse +from django.utils.datastructures import MultiValueDict as BaseMultiValueDict from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _, ugettext from django.template.defaultfilters import slugify @@ -47,6 +48,24 @@ class BColors: UNDERLINE = '\033[4m' +class MultiValueDict(BaseMultiValueDict): + def get(self, *args, **kwargs): + v = super(MultiValueDict, self).getlist(*args, **kwargs) + if callable(v): + v = v() + if type(v) in (list, tuple) and len(v) > 1: + v = ",".join(v) + elif type(v) not in (int, unicode): + v = super(MultiValueDict, self).get(*args, **kwargs) + return v + + def getlist(self, *args, **kwargs): + lst = super(MultiValueDict, self).getlist(*args, **kwargs) + if type(lst) not in (tuple, list): + lst = [lst] + return lst + + def get_current_year(): return datetime.datetime.now().year diff --git a/ishtar_common/wizards.py b/ishtar_common/wizards.py index f86e03df0..e82b32671 100644 --- a/ishtar_common/wizards.py +++ b/ishtar_common/wizards.py @@ -34,37 +34,19 @@ from django.db.models.fields.files import FileField, ImageFieldFile from django.db.models.fields.related import ManyToManyField from django.db.models.fields import NOT_PROVIDED -from django.http import HttpResponseRedirect +from django.http import HttpResponseRedirect, Http404 from django.forms import ValidationError from django.shortcuts import redirect, render from django.template import loader -from django.utils.datastructures import MultiValueDict as BaseMultiValueDict from django.utils.translation import ugettext_lazy as _ from ishtar_common import models -from ishtar_common.utils import get_all_field_names +from ishtar_common.forms import CustomForm +from ishtar_common.utils import get_all_field_names, MultiValueDict logger = logging.getLogger(__name__) -class MultiValueDict(BaseMultiValueDict): - def get(self, *args, **kwargs): - v = super(MultiValueDict, self).getlist(*args, **kwargs) - if callable(v): - v = v() - if type(v) in (list, tuple) and len(v) > 1: - v = ",".join(v) - elif type(v) not in (int, unicode): - v = super(MultiValueDict, self).get(*args, **kwargs) - return v - - def getlist(self, *args, **kwargs): - lst = super(MultiValueDict, self).getlist(*args, **kwargs) - if type(lst) not in (tuple, list): - lst = [lst] - return lst - - def check_rights(rights=[], redirect_url='/'): """ Decorator that checks the rights to access the view. @@ -125,6 +107,19 @@ def _check_right(step, condition=True): """ +def filter_no_fields_form(form, other_check=None): + def func(self): + if issubclass(form, CustomForm): + enabled, exc = form.check_availability_and_excluded_fields( + self.request.user.ishtaruser) + if not enabled: + return False + if other_check: + return other_check(self) + return True + return func + + class Wizard(NamedUrlWizardView): model = None label = '' @@ -155,6 +150,19 @@ class Wizard(NamedUrlWizardView): self.condition_dict[form_key] = cond ''' + @classmethod + def get_initkwargs(cls, *args, **kwargs): + kwargs = super(Wizard, cls).get_initkwargs(*args, **kwargs) + # remove + for form_key in kwargs['form_list']: + form = kwargs['form_list'][form_key] + other_check = None + if form_key in kwargs['condition_dict']: + other_check = kwargs['condition_dict'][form_key] + kwargs['condition_dict'][form_key] = filter_no_fields_form( + form, other_check) + return kwargs + def dispatch(self, request, *args, **kwargs): self.current_right = kwargs.get('current_right', None) @@ -813,7 +821,10 @@ class Wizard(NamedUrlWizardView): data = data.copy() if not step: step = self.steps.current - form = self.get_form_list()[step] + try: + form = self.get_form_list()[step] + except KeyError: + raise Http404() if hasattr(form, 'management_form'): # manage deletion to_delete, not_to_delete = self.get_deleted(data.keys()) -- cgit v1.2.3 From 1f49ac758d42cd924dd1df39af58835b80f1f77e Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Tue, 21 Nov 2017 15:26:41 +0100 Subject: Custom forms: manage formsets --- archaeological_finds/forms.py | 12 +-- archaeological_operations/forms.py | 84 ++++++++++------- archaeological_operations/views.py | 5 ++ ishtar_common/forms.py | 180 ++++++++++++++++++++++--------------- ishtar_common/tests.py | 2 +- 5 files changed, 173 insertions(+), 110 deletions(-) (limited to 'ishtar_common/forms.py') diff --git a/archaeological_finds/forms.py b/archaeological_finds/forms.py index b88ee164e..2a895064f 100644 --- a/archaeological_finds/forms.py +++ b/archaeological_finds/forms.py @@ -41,7 +41,7 @@ import models from ishtar_common.forms import FormSet, FloatField, \ get_form_selection, reverse_lazy, TableSelect, get_now, FinalForm, \ - ManageOldType + ManageOldType, FieldType from ishtar_common.forms_common import get_town_field, SourceSelect from ishtar_common.utils import convert_coordinates_to_point @@ -316,11 +316,11 @@ class PreservationForm(ManageOldType, forms.Form): widget=forms.Textarea) TYPES = [ - ('conservatory_state', models.ConservatoryState, False), - ('treatment_emergency', models.TreatmentEmergencyType, False), - ('preservation_to_consider', models.TreatmentType, True), - ('alteration', models.AlterationType, True), - ('alteration_cause', models.AlterationCauseType, True), + FieldType('conservatory_state', models.ConservatoryState), + FieldType('treatment_emergency', models.TreatmentEmergencyType), + FieldType('preservation_to_consider', models.TreatmentType, True), + FieldType('alteration', models.AlterationType, True), + FieldType('alteration_cause', models.AlterationCauseType, True), ] def __init__(self, *args, **kwargs): diff --git a/archaeological_operations/forms.py b/archaeological_operations/forms.py index 47fe746f5..4dd896966 100644 --- a/archaeological_operations/forms.py +++ b/archaeological_operations/forms.py @@ -49,7 +49,7 @@ from ishtar_common import widgets from ishtar_common.forms import FinalForm, FormSet, get_now, \ reverse_lazy, get_form_selection, TableSelect, get_data_from_formset, \ - ManageOldType, CustomForm + ManageOldType, CustomForm, FieldType from ishtar_common.forms_common import TownFormSet, SourceForm, SourceSelect, \ get_town_field @@ -763,8 +763,9 @@ class DashboardForm(forms.Form): class OperationFormGeneral(ManageOldType, CustomForm, forms.Form): form_label = _(u"General") - form_admin_name = _(u"Operation - General") - form_slug = "operation-general" + form_admin_name = _(u"Operation - General - Creation") + form_slug = "operation-general-creation" + file_upload = True associated_models = {'scientist': Person, 'in_charge': Person, @@ -884,33 +885,36 @@ class OperationFormGeneral(ManageOldType, CustomForm, forms.Form): 'height': settings.IMAGE_MAX_SIZE[1]}), max_length=255, required=False, widget=widgets.ImageFileInput()) + FILE_FIELDS = [ + 'report_delivery_date', + 'report_processing', + 'cira_rapporteur', + 'cira_date', + 'negative_result' + ] + WAREHOUSE_FIELDS = [ + 'documentation_deadline', + 'documentation_received', + 'finds_deadline', + 'finds_received', + ] + TYPES = [ + FieldType('operation_type', models.OperationType), + FieldType('report_processing', models.ReportState), + ] + def __init__(self, *args, **kwargs): super(OperationFormGeneral, self).__init__(*args, **kwargs) profile = get_current_profile() if not profile.files: - self.fields.pop('report_delivery_date') - self.fields.pop('report_processing') - self.fields.pop('cira_rapporteur') - self.fields.pop('cira_date') - self.fields.pop('negative_result') + for key in self.FILE_FIELDS: + self.remove_field(key) if not profile.warehouse: - self.fields.pop('documentation_deadline') - self.fields.pop('documentation_received') - self.fields.pop('finds_deadline') - self.fields.pop('finds_received') - self.fields['operation_type'].choices = \ - models.OperationType.get_types( - initial=self.init_data.get('operation_type')) - self.fields['operation_type'].help_text = \ - models.OperationType.get_help() - if 'report_processing' in self.fields: - self.fields['report_processing'].choices = \ - models.ReportState.get_types( - initial=self.init_data.get('report_processing')) - self.fields['report_processing'].help_text = \ - models.ReportState.get_help() - self.fields['record_quality'].choices = \ - [('', '--')] + list(models.QUALITY) + for key in self.WAREHOUSE_FIELDS: + self.remove_field(key) + if 'record_quality' in self.fields: + self.fields['record_quality'].choices = \ + [('', '--')] + list(models.QUALITY) if 'operation_code' in self.fields: fields = OrderedDict() ope_code = self.fields.pop('operation_code') @@ -922,17 +926,20 @@ class OperationFormGeneral(ManageOldType, CustomForm, forms.Form): def clean(self): cleaned_data = self.cleaned_data + # verify the logic between start date and excavation end date - if cleaned_data.get('excavation_end_date'): + if self.are_available(['excavation_end_date', 'start_date']) \ + and cleaned_data.get('excavation_end_date'): if not self.cleaned_data['start_date']: raise forms.ValidationError( - _(u"If you want to set an excavation end date you have to " - u"provide a start date.")) + _(u"If you want to set an excavation end date you " + u"have to provide a start date.")) if cleaned_data['excavation_end_date'] \ < cleaned_data['start_date']: raise forms.ValidationError( _(u"The excavation end date cannot be before the start " u"date.")) + # verify patriarche code_p = self.cleaned_data.get('code_patriarche', None) @@ -944,11 +951,13 @@ class OperationFormGeneral(ManageOldType, CustomForm, forms.Form): msg = u"Ce code OA a déjà été affecté à une "\ u"autre opération" raise forms.ValidationError(msg) + # manage unique operation ID year = self.cleaned_data.get("year") operation_code = cleaned_data.get("operation_code", None) if not operation_code: return self.cleaned_data + ops = models.Operation.objects.filter(year=year, operation_code=operation_code) if 'pk' in cleaned_data and cleaned_data['pk']: @@ -969,6 +978,9 @@ class OperationFormGeneral(ManageOldType, CustomForm, forms.Form): class OperationFormModifGeneral(OperationFormGeneral): + form_admin_name = _(u"Operation - General - Modification") + form_slug = "operation-general-modification" + operation_code = forms.IntegerField(label=_(u"Operation code"), required=False) currents = {'associated_file': File} @@ -991,6 +1003,7 @@ class OperationFormModifGeneral(OperationFormGeneral): fields[key] = value self.fields = fields + OperationFormModifGeneral.associated_models = \ OperationFormGeneral.associated_models.copy() @@ -1001,6 +1014,7 @@ class CollaboratorForm(CustomForm, forms.Form): form_label = _(u"Collaborators") form_admin_name = _(u"Operation - Collaborators") form_slug = "operation-collaborators" + base_models = ['collaborator'] associated_models = {'collaborator': Person, } collaborator = widgets.Select2MultipleField( @@ -1012,8 +1026,11 @@ class CollaboratorForm(CustomForm, forms.Form): self.fields['collaborator'].widget.attrs['full-width'] = True -class OperationFormPreventive(forms.Form): +class OperationFormPreventive(CustomForm, forms.Form): form_label = _(u"Preventive informations - excavation") + form_admin_name = _(u"Operation - Preventive - Excavation") + form_slug = "operation-preventive-excavation" + cost = forms.IntegerField(label=_(u"Cost (euros)"), required=False) scheduled_man_days = forms.IntegerField(label=_(u"Scheduled man-days"), required=False) @@ -1028,8 +1045,11 @@ class OperationFormPreventive(forms.Form): validators.MaxValueValidator(100)]) -class OperationFormPreventiveDiag(forms.Form): +class OperationFormPreventiveDiag(CustomForm, forms.Form): form_label = _("Preventive informations - diagnostic") + form_admin_name = _(u"Operation - Preventive - Diagnostic") + form_slug = "operation-preventive-diagnostic" + if settings.COUNTRY == 'fr': zoning_prescription = forms.NullBooleanField( required=False, label=_(u"Prescription on zoning")) @@ -1054,6 +1074,7 @@ class SelectedTownForm(forms.Form): if towns and towns != -1: self.fields['town'].choices = [('', '--')] + towns + SelectedTownFormset = formset_factory(SelectedTownForm, can_delete=True, formset=TownFormSet) SelectedTownFormset.form_label = _(u"Towns") @@ -1202,6 +1223,9 @@ class ArchaeologicalSiteBasicForm(forms.Form): ArchaeologicalSiteFormSet = formset_factory(ArchaeologicalSiteBasicForm, can_delete=True, formset=FormSet) ArchaeologicalSiteFormSet.form_label = _("Archaeological sites") +ArchaeologicalSiteFormSet.form_admin_name = _("Operation - Archaeological " + "sites") +ArchaeologicalSiteFormSet.form_slug = "operation-archaeological-sites" class ArchaeologicalSiteSelectionForm(forms.Form): diff --git a/archaeological_operations/views.py b/archaeological_operations/views.py index 1fecce9cd..c078d910d 100644 --- a/archaeological_operations/views.py +++ b/archaeological_operations/views.py @@ -84,6 +84,7 @@ def autocomplete_archaeologicalsite(request): for site in sites]) return HttpResponse(data, content_type='text/plain') + new_archaeologicalsite = new_item(models.ArchaeologicalSite, ArchaeologicalSiteForm, many=True) @@ -136,6 +137,7 @@ def get_available_operation_code(request, year=None): models.Operation.get_available_operation_code(year)}) return HttpResponse(data, content_type='text/plain') + get_operation = get_item(models.Operation, 'get_operation', 'operation') show_operation = show_item(models.Operation, 'operation') @@ -162,11 +164,13 @@ def dashboard_operation(request, *args, **kwargs): dct = {'dashboard': models.OperationDashboard()} return render(request, 'ishtar/dashboards/dashboard_operation.html', dct) + operation_search_wizard = SearchWizard.as_view( [('general-operation_search', OperationFormSelection)], label=_(u"Operation search"), url_name='operation_search',) + wizard_steps = [ ('filechoice-operation_creation', OperationFormFileChoice), ('general-operation_creation', OperationFormGeneral), @@ -195,6 +199,7 @@ def get_check_files_for_operation(other_check=None): return other_check(self) return func + check_files_for_operation = get_check_files_for_operation() diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index da6a1c051..8b97cfbab 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -105,7 +105,92 @@ def get_readonly_clean(key): return func -class FormSet(BaseFormSet): +class CustomForm(object): + form_admin_name = "" + form_slug = "" + need_user_for_initialization = True + + def __init__(self, *args, **kwargs): + current_user = None + if 'user' in kwargs: + try: + current_user = kwargs.pop('user').ishtaruser + except AttributeError: + pass + super(CustomForm, self).__init__(*args, **kwargs) + available, excluded = self.check_availability_and_excluded_fields( + current_user) + for exc in excluded: + if hasattr(self, 'fields'): + self.remove_field(exc) + else: + # formset + for form in self.forms: + if exc in form.fields: + form.fields.pop(exc) + + def are_available(self, keys): + for k in keys: + if k not in self.fields: + return False + return True + + def remove_field(self, key): + if key in self.fields: + self.fields.pop(key) + + @classmethod + def check_availability_and_excluded_fields(cls, current_user): + if not current_user: + return True, [] + base_q = {"form": cls.form_slug, 'available': True} + # order is important : try for user, user type then all + query_dicts = [] + if current_user: + dct = base_q.copy() + dct.update({'users__pk': current_user.pk}) + query_dicts = [dct] + for user_type in current_user.person.person_types.all(): + dct = base_q.copy() + dct.update({'user_types__pk': user_type.pk}), + query_dicts.append(dct) + dct = base_q.copy() + dct.update({'apply_to_all': True}) + query_dicts.append(dct) + excluded_lst = [] + for query_dict in query_dicts: + q = models.CustomForm.objects.filter(**query_dict) + if not q.count(): + continue + # todo: prevent multiple result in database + form = q.all()[0] + if not form.enabled: + return False, [] + for excluded in form.excluded_fields.all(): + # could have be filtered previously + excluded_lst.append(excluded.field) + break + return True, excluded_lst + + @classmethod + def get_custom_fields(cls): + if hasattr(cls, 'base_fields'): + fields = cls.base_fields + else: + # formset + fields = cls.form.base_fields + customs = [] + for key in fields: + field = fields[key] + # cannot customize display of required and hidden field + # field with no label are also rejected + if field.required or field.widget.is_hidden or not field.label: + continue + customs.append((key, field.label)) + return sorted(customs, key=lambda x: x[1]) + + +class FormSet(CustomForm, BaseFormSet): def __init__(self, *args, **kwargs): self.readonly = False if 'readonly' in kwargs: @@ -250,8 +335,23 @@ def get_data_from_formset(data): return values +class FieldType(object): + def __init__(self, key, model, is_multiple=False): + self.key = key + self.model = model + self.is_multiple = is_multiple + + def get_choices(self, initial=None): + return self.model.get_types( + empty_first=not self.is_multiple, + initial=initial) + + def get_help(self): + return self.model.get_help() + + class ManageOldType(object): - TYPES = [] # (field_name, model, is_multiple) list + TYPES = [] # FieldType list def __init__(self, *args, **kwargs): """ @@ -290,78 +390,12 @@ class ManageOldType(object): self.init_data[k].append(val) self.init_data = MultiValueDict(self.init_data) super(ManageOldType, self).__init__(*args, **kwargs) - for field_name, model, is_multiple in self.TYPES: - self.fields[field_name].choices = \ - model.get_types( - empty_first=not is_multiple, - initial=self.init_data.get(field_name)) - self.fields[field_name].help_text = model.get_help() - - -class CustomForm(object): - form_admin_name = "" - form_slug = "" - need_user_for_initialization = True - - def __init__(self, *args, **kwargs): - current_user = None - if 'user' in kwargs: - try: - current_user = kwargs.pop('user').ishtaruser - except AttributeError: - pass - super(CustomForm, self).__init__(*args, **kwargs) - available, excluded = self.check_availability_and_excluded_fields( - current_user) - for exc in excluded: - if exc in self.fields: - self.fields.pop(exc) - - @classmethod - def check_availability_and_excluded_fields(cls, current_user): - if not current_user: - return True, [] - base_q = {"form": cls.form_slug, 'available': True} - # order is important : try for user, user type then all - query_dicts = [] - if current_user: - dct = base_q.copy() - dct.update({'users__pk': current_user.pk}) - query_dicts = [dct] - for user_type in current_user.person.person_types.all(): - dct = base_q.copy() - dct.update({'user_types__pk': user_type.pk}), - query_dicts.append(dct) - dct = base_q.copy() - dct.update({'apply_to_all': True}) - query_dicts.append(dct) - excluded_lst = [] - for query_dict in query_dicts: - q = models.CustomForm.objects.filter(**query_dict) - if not q.count(): + for field in self.TYPES: + if field.key not in self.fields: continue - # todo: prevent multiple result in database - form = q.all()[0] - if not form.enabled: - return False, [] - for excluded in form.excluded_fields.all(): - # could have be filtered previously - excluded_lst.append(excluded.field) - break - return True, excluded_lst - - @classmethod - def get_custom_fields(cls): - fields = cls.base_fields - customs = [] - for key in fields: - field = fields[key] - # cannot customize display of required and hidden field - # field with no label are also rejected - if field.required or field.widget.is_hidden or not field.label: - continue - customs.append((key, field.label)) - return sorted(customs, key=lambda x: x[1]) + self.fields[field.key].choices = field.get_choices( + initial=self.init_data.get(field.key)) + self.fields[field.key].help_text = field.get_help() class DocumentGenerationForm(forms.Form): diff --git a/ishtar_common/tests.py b/ishtar_common/tests.py index 016596772..7c8b2fd5c 100644 --- a/ishtar_common/tests.py +++ b/ishtar_common/tests.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Copyright (C) 2015-2016 Étienne Loks +# Copyright (C) 2015-2017 Étienne Loks # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as -- cgit v1.2.3 From 658fc191a03416eedf7cbe808d539af589123e8e Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Tue, 21 Nov 2017 16:56:36 +0100 Subject: Custom form: operations forms --- archaeological_operations/forms.py | 85 ++++++++++++++++++++------------------ ishtar_common/forms.py | 18 +++++--- ishtar_common/forms_common.py | 15 ++++--- 3 files changed, 67 insertions(+), 51 deletions(-) (limited to 'ishtar_common/forms.py') diff --git a/archaeological_operations/forms.py b/archaeological_operations/forms.py index 4dd896966..6966fff50 100644 --- a/archaeological_operations/forms.py +++ b/archaeological_operations/forms.py @@ -477,6 +477,8 @@ class RecordRelationsFormSetBase(FormSet): RecordRelationsFormSet = formset_factory( RecordRelationsForm, can_delete=True, formset=RecordRelationsFormSetBase) RecordRelationsFormSet.form_label = _(u"Relations") +RecordRelationsFormSet.form_admin_name = _("Operations - Relations") +RecordRelationsFormSet.form_slug = "operation-relations" class OperationSelect(TableSelect): @@ -675,12 +677,15 @@ class OperationFormFileChoice(forms.Form): validators=[valid_id(File)], required=False) -class OperationFormAbstract(forms.Form): +class OperationFormAbstract(CustomForm, forms.Form): form_label = _(u"Abstract") + form_admin_name = _("Operations - Abstract") + form_slug = "operation-abstract" abstract = forms.CharField( label=_(u"Abstract"), widget=forms.Textarea(attrs={'class': 'xlarge'}), required=False) + SLICING = (("month", _(u"months")), ('year', _(u"years")),) DATE_SOURCE = (('creation', _(u"Creation date")), @@ -763,8 +768,8 @@ class DashboardForm(forms.Form): class OperationFormGeneral(ManageOldType, CustomForm, forms.Form): form_label = _(u"General") - form_admin_name = _(u"Operation - General - Creation") - form_slug = "operation-general-creation" + form_admin_name = _(u"Operation - General") + form_slug = "operation-general" file_upload = True associated_models = {'scientist': Person, @@ -978,9 +983,6 @@ class OperationFormGeneral(ManageOldType, CustomForm, forms.Form): class OperationFormModifGeneral(OperationFormGeneral): - form_admin_name = _(u"Operation - General - Modification") - form_slug = "operation-general-modification" - operation_code = forms.IntegerField(label=_(u"Operation code"), required=False) currents = {'associated_file': File} @@ -1078,6 +1080,7 @@ class SelectedTownForm(forms.Form): SelectedTownFormset = formset_factory(SelectedTownForm, can_delete=True, formset=TownFormSet) SelectedTownFormset.form_label = _(u"Towns") +SelectedTownFormset.form_slug = "towns" class SelectedParcelForm(forms.Form): @@ -1094,13 +1097,17 @@ class SelectedParcelForm(forms.Form): if parcels: self.fields['parcel'].choices = [('', '--')] + parcels + SelectedParcelFormSet = formset_factory(SelectedParcelForm, can_delete=True, formset=ParcelFormSet) SelectedParcelFormSet.form_label = _("Parcels") +SelectedParcelFormSet.form_admin_name = _(u"Operations - Parcels") +SelectedParcelFormSet.form_slug = "operation-parcels" SelectedParcelGeneralFormSet = formset_factory(ParcelForm, can_delete=True, formset=ParcelFormSet) -SelectedParcelGeneralFormSet.form_label = _("Parcels") +SelectedParcelGeneralFormSet.form_admin_name = _("Parcels") +SelectedParcelGeneralFormSet.form_slug = "operation-parcels" """ class SelectedParcelFormSet(forms.Form): @@ -1128,36 +1135,36 @@ class SelectedParcelFormSet(forms.Form): """ -class RemainForm(ManageOldType, forms.Form): +class RemainForm(CustomForm, ManageOldType, forms.Form): form_label = _("Remain types") + form_admin_name = _("Operations - Remains") + form_slug = "operation-remains" + base_model = 'remain' associated_models = {'remain': models.RemainType} remain = forms.MultipleChoiceField( label=_("Remain type"), required=False, choices=[], widget=forms.CheckboxSelectMultiple) - def __init__(self, *args, **kwargs): - super(RemainForm, self).__init__(*args, **kwargs) - self.fields['remain'].choices = models.RemainType.get_types( - initial=self.init_data.get('remain'), - empty_first=False) - self.fields['remain'].help_text = models.RemainType.get_help() + TYPES = [ + FieldType('remain', models.RemainType, True), + ] -class PeriodForm(ManageOldType, forms.Form): +class PeriodForm(CustomForm, ManageOldType, forms.Form): form_label = _("Periods") + form_admin_name = _("Operations - Periods") + form_slug = "operation-periods" + base_model = 'period' associated_models = {'period': models.Period} period = forms.MultipleChoiceField( label=_("Period"), required=False, choices=[], widget=forms.CheckboxSelectMultiple) - def __init__(self, *args, **kwargs): - super(PeriodForm, self).__init__(*args, **kwargs) - self.fields['period'].choices = models.Period.get_types( - initial=self.init_data.get('period'), - empty_first=False) - self.fields['period'].help_text = models.Period.get_help() + TYPES = [ + FieldType('period', models.Period, True), + ] class ArchaeologicalSiteForm(ManageOldType, forms.Form): @@ -1170,21 +1177,16 @@ class ArchaeologicalSiteForm(ManageOldType, forms.Form): label=_("Remains"), choices=[], widget=widgets.Select2Multiple, required=False) + TYPES = [ + FieldType('periods', models.Period, True), + FieldType('remains', models.RemainType, True), + ] + def __init__(self, *args, **kwargs): self.limits = {} if 'limits' in kwargs: kwargs.pop('limits') super(ArchaeologicalSiteForm, self).__init__(*args, **kwargs) - self.fields['periods'].choices = \ - models.Period.get_types( - empty_first=False, - initial=self.init_data.get('periods')) - self.fields['periods'].help_text = models.Period.get_help() - self.fields['remains'].choices = \ - models.RemainType.get_types( - initial=self.init_data.get('remains'), - empty_first=False) - self.fields['remains'].help_text = models.RemainType.get_help() def clean_reference(self): reference = self.cleaned_data['reference'] @@ -1253,6 +1255,9 @@ class OperationDeletionForm(FinalForm): class OperationSourceForm(SourceForm): + form_admin_name = _("Operation Sources - Main") + form_slug = "operation-source-relations" + pk = forms.IntegerField(required=False, widget=forms.HiddenInput) index = forms.IntegerField(label=_(u"Index")) hidden_operation_id = forms.IntegerField(label="", @@ -1400,8 +1405,11 @@ class AdministrativeActOpeFormSelection(forms.Form): return cleaned_data -class AdministrativeActOpeForm(ManageOldType, forms.Form): +class AdministrativeActOpeForm(CustomForm, ManageOldType, forms.Form): form_label = _("General") + form_admin_name = _("Operations - Administrative act - General") + form_slug = "operation-adminact-general" + associated_models = {'act_type': models.ActType, } # 'signatory':Person} act_type = forms.ChoiceField(label=_("Act type"), choices=[]) @@ -1417,13 +1425,10 @@ class AdministrativeActOpeForm(ManageOldType, forms.Form): ref_sra = forms.CharField(label=u"Autre référence", max_length=15, required=False) - def __init__(self, *args, **kwargs): - super(AdministrativeActOpeForm, self).__init__(*args, **kwargs) - self.fields['act_type'].choices = models.ActType.get_types( - initial=self.init_data.get('act_type'), - dct={'intented_to': 'O'}) - self.fields['act_type'].help_text = models.ActType.get_help( - dct={'intented_to': 'O'}) + TYPES = [ + FieldType('act_type', models.ActType, + extra_args={"dct": {'intented_to': 'O'}}), + ] class AdministrativeActModifForm(object): @@ -1439,7 +1444,7 @@ class AdministrativeActModifForm(object): def clean(self): # manage unique act ID - year = self.cleaned_data.get("signature_date") + year = self.cleaned_data.get("signature_date", None) if not year or not hasattr(year, 'year'): return self.cleaned_data year = year.year diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index 8b97cfbab..eebd912ea 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -336,18 +336,26 @@ def get_data_from_formset(data): class FieldType(object): - def __init__(self, key, model, is_multiple=False): + def __init__(self, key, model, is_multiple=False, extra_args=None): self.key = key self.model = model self.is_multiple = is_multiple + self.extra_args = extra_args def get_choices(self, initial=None): - return self.model.get_types( - empty_first=not self.is_multiple, - initial=initial) + args = { + 'empty_first': not self.is_multiple, + 'initial': initial + } + if self.extra_args: + args.update(self.extra_args) + return self.model.get_types(**args) def get_help(self): - return self.model.get_help() + args = {} + if self.extra_args: + args.update(self.extra_args) + return self.model.get_help(**args) class ManageOldType(object): diff --git a/ishtar_common/forms_common.py b/ishtar_common/forms_common.py index 116c8c277..32c91b683 100644 --- a/ishtar_common/forms_common.py +++ b/ishtar_common/forms_common.py @@ -35,7 +35,7 @@ import models import widgets from ishtar_common.templatetags.link_to_window import link_to_window from forms import FinalForm, FormSet, reverse_lazy, name_validator, \ - TableSelect, ManageOldType + TableSelect, ManageOldType, CustomForm, FieldType def get_town_field(label=_(u"Town"), required=True): @@ -733,6 +733,8 @@ class TownFormSet(FormSet): TownFormset = formset_factory(TownForm, can_delete=True, formset=TownFormSet) TownFormset.form_label = _("Towns") +TownFormset.form_admin_name = _(u"Towns") +TownFormset.form_slug = "towns" class MergeFormSet(BaseModelFormSet): @@ -860,7 +862,7 @@ class MergeOrganizationForm(MergeForm): ###################### # Sources management # ###################### -class SourceForm(ManageOldType, forms.Form): +class SourceForm(CustomForm, ManageOldType, forms.Form): form_label = _(u"Documentation informations") file_upload = True associated_models = {'source_type': models.SourceType} @@ -899,10 +901,9 @@ class SourceForm(ManageOldType, forms.Form): 'height': settings.IMAGE_MAX_SIZE[1]}), max_length=255, required=False, widget=widgets.ImageFileInput()) - def __init__(self, *args, **kwargs): - super(SourceForm, self).__init__(*args, **kwargs) - self.fields['source_type'].choices = models.SourceType.get_types( - initial=self.init_data.get('source_type')) + TYPES = [ + FieldType('source_type', models.SourceType), + ] class SourceSelect(TableSelect): @@ -986,3 +987,5 @@ class AuthorFormSet(FormSet): AuthorFormset = formset_factory(AuthorFormSelection, can_delete=True, formset=AuthorFormSet) AuthorFormset.form_label = _("Authors") +AuthorFormset.form_admin_name = _(u"Authors") +AuthorFormset.form_slug = "authors" -- cgit v1.2.3