summaryrefslogtreecommitdiff
path: root/ishtar_common/forms.py
blob: 043b03f61b3a3468156a6ab62133f6b53e495e18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2016 Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

"""
Forms definition
"""
import datetime
import re

from django import forms
from django.core.urlresolvers import reverse
from django.core import validators
from django.forms.formsets import BaseFormSet, DELETION_FIELD_NAME
from django.utils import formats
from django.utils.functional import lazy
from django.utils.translation import ugettext_lazy as _

import models
import widgets


# from formwizard.forms import NamedUrlSessionFormWizard


class NamedUrlSessionFormWizard(forms.Form):
    def __init__(self, form_list, condition_list={}, url_name=''):
        self.form_list = dict(form_list)
        self.condition_list = condition_list
        self.url_name = url_name
        super(NamedUrlSessionFormWizard, self).__init__(self)

    def rindex(self, idx):
        return self.url_name.rindex(idx)


def my_reverse(*args, **kwargs):
    """
    Custom reverse method in order to evaluate lazy args
    """
    if 'args' in kwargs:
        my_args = []
        for arg in kwargs['args']:
            if callable(arg):
                my_args.append(unicode(arg()))
            else:
                my_args.append(unicode(arg))
        kwargs['args'] = my_args
    return reverse(*args, **kwargs)


reverse_lazy = lazy(my_reverse, unicode)

regexp_name = re.compile(r"^[,:/\w\-'\"() \&\[\]@]+$", re.UNICODE)
name_validator = validators.RegexValidator(
    regexp_name,
    _(u"Enter a valid name consisting of letters, spaces and hyphens."),
    'invalid')


class FloatField(forms.FloatField):
    """
    Allow the use of comma for separating float fields
    """
    def clean(self, value):
        if value:
            value = value.replace(',', '.').replace('%', '')
        return super(FloatField, self).clean(value)


class FinalForm(forms.Form):
    final = True
    form_label = _(u"Confirm")


class FinalDeleteForm(FinalForm):
    confirm_msg = " "
    confirm_end_msg = _(u"Are you sure you want to delete?")


class FormSet(BaseFormSet):
    def check_duplicate(self, key_names, error_msg=""):
        """Check for duplicate items in the formset"""
        if any(self.errors):
            return
        if not error_msg:
            error_msg = _("There are identical items.")
        items = []
        for i in range(0, self.total_form_count()):
            form = self.forms[i]
            if not form.is_valid():
                continue
            item = [key_name in form.cleaned_data and
                    form.cleaned_data[key_name]
                    for key_name in key_names]
            if not [v for v in item if v]:
                continue
            if item in items:
                raise forms.ValidationError, error_msg
            items.append(item)

    def add_fields(self, form, index):
        super(FormSet, self).add_fields(form, index)
        form.fields[DELETION_FIELD_NAME].label = ''
        form.fields[DELETION_FIELD_NAME].widget = widgets.DeleteWidget()


class TableSelect(forms.Form):
    def __init__(self, *args, **kwargs):
        super(TableSelect, self).__init__(*args, **kwargs)
        key = self.fields.keyOrder[0]
        self.fields[key].widget.attrs['autofocus'] = 'autofocus'

    def get_input_ids(self):
        return self.fields.keys()


def get_now():
    format = formats.get_format('DATE_INPUT_FORMATS')[0]
    value = datetime.datetime.now().strftime(format)
    return value


class ClosingDateFormSelection(forms.Form):
    form_label = _("Closing date")
    end_date = forms.DateField(label=_(u"Closing date"),
                               widget=widgets.JQueryDate)

    def __init__(self, *args, **kwargs):
        if 'initial' not in kwargs:
            kwargs['initial'] = {}
        if not kwargs['initial'].get('end_date', None):
            kwargs['initial']['end_date'] = datetime.date.today()
        super(ClosingDateFormSelection, self).__init__(*args, **kwargs)


def get_form_selection(
        class_name, label, key, model, base_form, get_url,
        not_selected_error=_(u"You should select an item."), new=False,
        new_message=_(u"Add a new item"), get_full_url=None):
    """
    Generate a class selection form
        class_name -- name of the class
        label -- label of the form
        key -- model,
        base_form -- base form to select
        get_url -- url to get the item
        not_selected_error -- message displayed when no item is selected
        new -- can add new items
        new_message -- message of link to add new items
    """
    attrs = {'_main_key': key,
             '_not_selected_error': not_selected_error,
             'form_label': label,
             'associated_models': {key: model},
             'currents': {key: model}}
    widget_kwargs = {"new": new, "new_message": new_message}
    if get_full_url:
        widget_kwargs['source_full'] = reverse_lazy(get_full_url)
    attrs[key] = forms.IntegerField(
        label="", required=False,
        validators=[models.valid_id(model)],
        widget=widgets.JQueryJqGrid(reverse_lazy(get_url), base_form, model,
                                    **widget_kwargs))

    def clean(self):
        cleaned_data = self.cleaned_data
        if self._main_key not in cleaned_data \
           or not cleaned_data[self._main_key]:
            raise forms.ValidationError(self._not_selected_error)
        return cleaned_data
    attrs['clean'] = clean
    return type(class_name, (forms.Form,), attrs)


def get_data_from_formset(data):
    """
    convert ['formname-wizardname-1-public_domain': [u'on'], ...] to
    [{'public_domain': 'off'}, {'public_domain': 'on'}]
    """
    values = []
    for k in data:
        if not data[k]:
            continue
        keys = k.split('-')
        if len(keys) < 3:
            continue
        try:
            idx = int(keys[-2])
        except ValueError:
            continue
        while len(values) < (idx + 1):
            values.append({})
        field_name = keys[-1]
        values[idx][field_name] = data[k]
    return values


class ManageOldType(object):
    def __init__(self, *args, **kwargs):
        """
        init_data is used to manage deactivated items in list when editing
        old data
        """
        prefix = kwargs.get('prefix') or ''
        self.init_data = {}
        if 'data' in kwargs and kwargs['data']:
            for k in kwargs['data']:
                if prefix not in k:
                    continue
                new_k = k[len(prefix) + 1:]
                items = []
                if hasattr(kwargs['data'], 'getlist'):
                    items = kwargs['data'].getlist(k)
                else:
                    items = [kwargs['data'][k]]
                for val in items:
                    if not val:
                        continue
                    if new_k not in self.init_data:
                        self.init_data[new_k] = []
                    self.init_data[new_k].append(val)
        if 'initial' in kwargs and kwargs['initial']:
            for k in kwargs['initial']:
                if k not in self.init_data or not self.init_data[k]:
                    items = []
                    if hasattr(kwargs['initial'], 'getlist'):
                        items = kwargs['initial'].getlist(k)
                    else:
                        items = [kwargs['initial'][k]]
                    for val in items:
                        if not val:
                            continue
                        if k not in self.init_data:
                            self.init_data[k] = []
                        self.init_data[k].append(val)
        super(ManageOldType, self).__init__(*args, **kwargs)


class DocumentGenerationForm(forms.Form):
    """
    Form to generate document by choosing the template
    """
    _associated_model = None  # ex: AdministrativeAct
    # ex: 'archaeological_operations.models.AdministrativeAct'
    _associated_object_name = ''
    document_template = forms.ChoiceField(label=_("Template"), choices=[])

    def __init__(self, *args, **kwargs):
        super(DocumentGenerationForm, self).__init__(*args, **kwargs)
        self.fields['document_template'].choices = \
            models.DocumentTemplate.get_tuples(
                dct={'associated_object_name': self._associated_object_name})

    def save(self, object_pk):
        try:
            c_object = self._associated_model.objects.get(pk=object_pk)
        except self._associated_model.DoesNotExist:
            return
        try:
            template = models.DocumentTemplate.objects.get(
                pk=self.cleaned_data.get('document_template'))
        except models.DocumentTemplate.DoesNotExist:
            return
        return template.publish(c_object)