summaryrefslogtreecommitdiff
path: root/archaeological_finds/forms.py
diff options
context:
space:
mode:
Diffstat (limited to 'archaeological_finds/forms.py')
-rw-r--r--archaeological_finds/forms.py133
1 files changed, 118 insertions, 15 deletions
diff --git a/archaeological_finds/forms.py b/archaeological_finds/forms.py
index e25d52805..271ee0c9d 100644
--- a/archaeological_finds/forms.py
+++ b/archaeological_finds/forms.py
@@ -21,6 +21,9 @@
Finds forms definitions
"""
+import datetime
+import logging
+
from django import forms
from django.conf import settings
from django.core import validators
@@ -30,7 +33,7 @@ from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from ishtar_common.models import Person, valid_id, valid_ids, \
- get_current_profile
+ get_current_profile, Organization
from archaeological_operations.models import Period, ArchaeologicalSite, \
RelationType as OpeRelationType
from archaeological_context_records.models import DatingType, DatingQuality, \
@@ -45,6 +48,8 @@ from ishtar_common.forms import FormSet, FloatField, \
ManageOldType
from ishtar_common.forms_common import get_town_field, SourceSelect
+logger = logging.getLogger(__name__)
+
class RecordFormSelection(forms.Form):
form_label = _("Context record")
@@ -592,57 +597,155 @@ class TreatmentFormSelection(forms.Form):
class BaseTreatmentForm(ManageOldType, SelectFindBasketForm):
form_label = _(u"Base treatment")
+ base_models = ['treatment_type']
associated_models = {'treatment_type': models.TreatmentType,
'person': Person,
'location': Warehouse,
+ 'organization': Organization,
+ 'container': models.Container,
'basket': models.FindBasket}
- treatment_type = forms.ChoiceField(label=_(u"Treatment type"), choices=[])
+ need_user_for_initialization = True
+
+ label = forms.CharField(label=_(u"Label"),
+ max_length=200, required=False)
+ other_reference = forms.CharField(
+ label=_(u"Other ref."), max_length=200, required=False)
+ year = forms.IntegerField(label=_("Year"),
+ initial=lambda: datetime.datetime.now().year,
+ validators=[validators.MinValueValidator(1900),
+ validators.MaxValueValidator(2100)])
+ treatment_type = forms.MultipleChoiceField(
+ label=_(u"Treatment type"), choices=[],
+ widget=forms.CheckboxSelectMultiple)
+ target_is_basket = forms.NullBooleanField(label=_(u"Target"))
person = forms.IntegerField(
- label=_(u"Doer"),
+ label=_(u"Responsible"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-person'), associated_model=Person,
new=True),
- validators=[valid_id(Person)])
+ validators=[valid_id(Person)], required=False)
+ organization = forms.IntegerField(
+ label=_(u"Organization"),
+ widget=widgets.JQueryAutoComplete(
+ reverse_lazy('autocomplete-organization'),
+ associated_model=Organization, new=True),
+ validators=[valid_id(Organization)], required=False)
location = forms.IntegerField(
label=_(u"Location"),
widget=widgets.JQueryAutoComplete(
reverse_lazy('autocomplete-warehouse'), associated_model=Warehouse,
new=True),
validators=[valid_id(Warehouse)])
+ container = forms.IntegerField(
+ label=_(u"Container (relevant for packaging)"),
+ widget=widgets.JQueryAutoComplete(
+ reverse_lazy('autocomplete-container'),
+ associated_model=models.Container, new=True),
+ validators=[valid_id(models.Container)], required=False)
+ external_id = forms.CharField(
+ label=_(u"External ref."), max_length=200, required=False)
+ comment = forms.CharField(label=_(u"Comment"),
+ widget=forms.Textarea, required=False)
description = forms.CharField(label=_(u"Description"),
widget=forms.Textarea, required=False)
+ goal = forms.CharField(label=_(u"Goal"),
+ widget=forms.Textarea, required=False)
start_date = forms.DateField(label=_(u"Start date"), required=False,
widget=widgets.JQueryDate)
end_date = forms.DateField(label=_(u"End date"), required=False,
widget=widgets.JQueryDate)
+ image = forms.ImageField(
+ label=_(u"Image"), help_text=mark_safe(
+ _(u"<p>Heavy images are resized to: %(width)dx%(height)d "
+ u"(ratio is preserved).</p>") % {
+ 'width': settings.IMAGE_MAX_SIZE[0],
+ 'height': settings.IMAGE_MAX_SIZE[1]}),
+ max_length=255, required=False, widget=widgets.ImageFileInput())
def __init__(self, *args, **kwargs):
+ user = kwargs.pop('user')
super(BaseTreatmentForm, self).__init__(*args, **kwargs)
+ q = Person.objects.filter(ishtaruser__pk=user.pk)
+ if q.count():
+ person = q.all()[0]
+ self.fields['person'].initial = person.pk
+ if person.attached_to:
+ self.fields['organization'].initial = person.attached_to.pk
+ self.fields['target_is_basket'].widget.choices = \
+ ((False, _(u"Single find")), (True, _(u"Basket")))
self.fields['treatment_type'].choices = models.TreatmentType.get_types(
initial=self.init_data.get('treatment_type'),
- dct={'upstream_is_many': False, 'downstream_is_many': False}
+ dct={'upstream_is_many': False, 'downstream_is_many': False},
+ empty_first=False
)
self.fields['treatment_type'].help_text = \
models.TreatmentType.get_help(
dct={'upstream_is_many': False, 'downstream_is_many': False})
+ # TODO
+ self.fields.pop('basket')
+ """
self.fields['basket'].required = False
self.fields['basket'].help_text = \
_(u"Leave it blank if you want to select a single item")
self.fields.keyOrder.pop(self.fields.keyOrder.index('basket'))
self.fields.keyOrder.insert(self.fields.keyOrder.index('description'),
'basket')
+ """
def clean(self, *args, **kwargs):
- try:
- treatment = models.TreatmentType.objects.get(
- pk=self.cleaned_data['treatment_type'], available=True)
- except models.TreatmentType.DoesNotExist:
- raise forms.ValidationError(_(u"This treatment type is not "
- u"available."))
- if treatment.upstream_is_many and \
- not self.cleaned_data.get('basket'):
- raise forms.ValidationError(_(u"This treatment needs a basket."))
- return self.cleaned_data
+ data = self.cleaned_data
+ packaging = models.TreatmentType.get_cache('packaging')
+ if not packaging:
+ logger.warning("No 'packaging' treatment type defined")
+ return
+ if data.get('container', None) \
+ and str(packaging.pk) not in data.get('treatment_type', []):
+ raise forms.ValidationError(
+ _(u"The container field is attached to the treatment. If "
+ u"no packaging treatment is done it is not relevant."))
+ if not data.get('container', None) \
+ and str(packaging.pk) in data.get('treatment_type', []):
+ raise forms.ValidationError(
+ _(u"If a packaging treatment is done, the container field "
+ u"must be filled."))
+ if not data.get('person', None) and not data.get('organization', None):
+ raise forms.ValidationError(
+ _(u"A responsible or an organization must be defined."))
+ return data
+ # TODO
+ """
+ for treatment_type in self.cleaned_data.get('treatment_type', []):
+ try:
+ treatment = models.TreatmentType.objects.get(
+ pk=treatment_type, available=True)
+ except models.TreatmentType.DoesNotExist:
+ raise forms.ValidationError(_(u"This treatment type is not "
+ u"available."))
+ if treatment.upstream_is_many and \
+ not self.cleaned_data.get('basket'):
+ raise forms.ValidationError(_(u"This treatment needs a "
+ u"basket."))
+ """
+
+
+class ModifyTreatmentForm(BaseTreatmentForm):
+ index = forms.IntegerField(_(u"Index"))
+ id = forms.IntegerField(' ', widget=forms.HiddenInput, required=False)
+
+ def clean(self, *args, **kwargs):
+ super(ModifyTreatmentForm, self).clean(*args, **kwargs)
+ cleaned_data = self.cleaned_data
+ year = cleaned_data.get('year')
+ pk = cleaned_data.get('id')
+ index = cleaned_data.get('index')
+ q = models.Treatment.objects\
+ .filter(year=year, index=index).exclude(pk=pk)
+ if index and q.count():
+ raise forms.ValidationError(
+ _(u"Another treatment with this index exists for {}."
+ ).format(year))
+ return cleaned_data
+
"""
####################################