summaryrefslogtreecommitdiff
path: root/ishtar_common/forms.py
blob: 5faa232fb6aca276b923ffcd632451ff9e8813e8 (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2013  É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 itertools import groupby

from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.core import validators
from django.core.exceptions import ObjectDoesNotExist
from django.core.mail import send_mail
from django.db.models import Max
from django.forms.formsets import formset_factory, BaseFormSet, \
                                  DELETION_FIELD_NAME
from django.shortcuts import render_to_response
from django.template import Context, RequestContext, loader
from django.utils import formats
from django.utils.functional import lazy
from django.utils.translation import ugettext_lazy as _

# 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)

import models
import widgets

reverse_lazy = lazy(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 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 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 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")):
    """
    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},}
    attrs[key] = forms.IntegerField(label="", required=False,
        validators=[models.valid_id(model)],
        widget=widgets.JQueryJqGrid(reverse_lazy(get_url), base_form, model,
                                    new=new, new_message=new_message))
    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)

class DocumentGenerationForm(forms.Form):
    """
    Form to generate document by choosing the template
    """
    _associated_model = None # ex: AdministrativeAct
    _associated_object_name = '' # ex: 'archaeological_operations.models.AdministrativeAct'
    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)