Project

General

Profile

Download (7.25 KB) Statistics
| Branch: | Tag: | Revision:

calebasse / calebasse / personnes / forms.py @ 1a43d77a

1
# -*- coding: utf-8 -*-
2
from django import forms
3
from django.forms.models import (inlineformset_factory, modelformset_factory,
4
        BaseInlineFormSet, BaseModelFormSet)
5
from django.utils.translation import gettext_lazy as _
6
from django.contrib.auth.models import User
7

    
8
from calebasse.ressources.models import WorkerType, Service
9

    
10
from models import Worker, UserWorker, TimeTable, Holiday
11

    
12

    
13
class UserForm(forms.ModelForm):
14
    error_messages = {
15
        'duplicate_username': _("A user with that username already exists."),
16
        'password_mismatch': _("The two password fields didn't match."),
17
    }
18

    
19
    worker = forms.ModelChoiceField(label=_('Personnel'),
20
            queryset=Worker.objects.all(), empty_label=_('None'),
21
            required=False)
22
    password1 = forms.CharField(label=_("Password"),
23
        widget=forms.PasswordInput, required=False)
24
    password2 = forms.CharField(label=_("Password confirmation"),
25
        widget=forms.PasswordInput,
26
        help_text=_("Enter the same password as above, for verification."),
27
        required=False)
28

    
29
    def __init__(self, service=None, *args, **kwargs):
30
        self.service = service
31
        super(UserForm, self).__init__(*args, **kwargs)
32
        self.fields['worker'].queryset = Worker.objects.for_service(service)
33
        self.fields['username'].label = _('Identifiant')
34
        if self.instance:
35
            try:
36
                worker = self.instance.userworker.worker
37
                self.fields['worker'].initial = worker.pk
38
            except UserWorker.DoesNotExist:
39
                pass
40

    
41
    def clean_username(self):
42
        # Since User.username is unique, this check is redundant,
43
        # but it sets a nicer error message than the ORM. See #13147.
44
        username = self.cleaned_data["username"]
45
        if self.instance is None:
46
            try:
47
                User.objects.get(username=username)
48
                raise forms.ValidationError(self.error_messages['duplicate_username'])
49
            except User.DoesNotExist:
50
                pass
51
        return username
52

    
53
    def clean_password2(self):
54
        password1 = self.cleaned_data.get("password1")
55
        password2 = self.cleaned_data.get("password2")
56
        if password1 and password2 and password1 != password2:
57
            raise forms.ValidationError(
58
                self.error_messages['password_mismatch'])
59
        return password2
60

    
61
    class Meta:
62
        model = User
63
        fields = ('username', 'email', 'password1', 'password2', 'worker')
64

    
65
    def save(self, commit=True):
66
        import pdb
67
        pdb.set_trace()
68
        instance = super(UserForm, self).save(commit=False)
69
        if self.cleaned_data['password1']:
70
            instance.set_password(self.cleaned_data['password1'])
71
        worker = self.cleaned_data.get('worker')
72
        if worker is not None:
73
            self.first_name = worker.first_name
74
            self.last_name = worker.last_name
75
            def save_m2m():
76
                if UserWorker.objects.filter(user_ptr=self.instance):
77
                    userworker = self.instance.userworker
78
                    userworker.worker = worker
79
                    userworker.save()
80
                else:
81
                    UserWorker.objects.create(id=self.instance.id, worker=worker)
82
            self.save_m2m = save_m2m
83
        else:
84
            self.save_m2m = lambda: None
85
        if commit:
86
            instance.save()
87
            self.save_m2m()
88
        return instance
89

    
90
class WorkerSearchForm(forms.Form):
91
    last_name = forms.CharField(label=u'Nom', required=False)
92
    first_name = forms.CharField(label=u'Prénom', required=False)
93
    profession = forms.ModelChoiceField(label=u'Profession',
94
            queryset=WorkerType.objects.all(), required=False)
95

    
96
    INTERVENE_STATUS_CHOICES = {
97
            'a': u'Thérapeute',
98
            'b': u'Non-thérapeute'
99
    }
100

    
101
    intervene_status = forms.MultipleChoiceField(
102
        choices=INTERVENE_STATUS_CHOICES.iteritems(),
103
        widget=forms.CheckboxSelectMultiple,
104
        initial=INTERVENE_STATUS_CHOICES.keys(),
105
        required=False)
106

    
107
class WorkerIdForm(forms.ModelForm):
108
    class Meta:
109
        model = Worker
110
        fields = ('last_name', 'first_name', 'gender')
111

    
112
class WorkerServiceForm(forms.ModelForm):
113
    class Meta:
114
        model = Worker
115
        fields = ('services',)
116
        widgets = {
117
                'services': forms.CheckboxSelectMultiple,
118
        }
119

    
120

    
121
class BaseTimetableFormSet(BaseInlineFormSet):
122
    def __init__(self, weekday=None, *args, **kwargs):
123
        kwargs['queryset'] = kwargs.get('queryset', TimeTable.objects).filter(weekday=weekday)
124
        kwargs['initial'] = [{ 'services': Service.objects.all().values_list('pk', flat=True) }] * 3
125
        super(BaseTimetableFormSet, self).__init__(*args, **kwargs)
126

    
127

    
128
class BaseTimeTableForm(forms.ModelForm):
129
    class Meta:
130
        model = TimeTable
131
        widgets = {
132
                'services': forms.CheckboxSelectMultiple,
133
        }
134

    
135
TimetableFormSet = inlineformset_factory(Worker, TimeTable,
136
        formset=BaseTimetableFormSet,
137
        form=BaseTimeTableForm,
138
        fields=('start_time', 'end_time', 'start_date', 'end_date', 'services'))
139

    
140
class BaseHolidayForm(forms.ModelForm):
141
    class Meta:
142
        widgets = {
143
                'comment': forms.Textarea(attrs={'rows': 3}),
144
        }
145

    
146
HolidayFormSet = inlineformset_factory(
147
        Worker, Holiday,
148
        form=BaseHolidayForm,
149
        fields=('start_date', 'end_date', 'start_time', 'end_time', 'comment'))
150

    
151
class HolidaySearchForm(forms.Form):
152
    start_date = forms.DateField(required=False)
153
    end_date = forms.DateField(required=False)
154

    
155
    def clean(self):
156
        cleaned_data = super(HolidaySearchForm, self).clean()
157
        if cleaned_data.get('start_date') or cleaned_data.get('end_date'):
158
            if not cleaned_data.get('start_date') \
159
                   or not cleaned_data.get('end_date'):
160
                raise forms.ValidationError(u'Vous devez fournir une date de début et de fin')
161
            if cleaned_data['start_date'] > cleaned_data['end_date']:
162
                raise forms.ValidationError(u'La date de début doit être supérieure à la date de fin')
163
        return cleaned_data
164

    
165
class YearlyHolidayBaseFormSet(BaseModelFormSet):
166
    def __init__(self, *args, **kwargs):
167
        self.service = kwargs.pop('service', None)
168
        old_form = self.form
169
        self.form = lambda *args, **kwargs: old_form(*args, service=self.service, **kwargs)
170
        super(YearlyHolidayBaseFormSet, self).__init__(*args, **kwargs)
171

    
172
class YearlyHolidayForm(forms.ModelForm):
173
    for_all_services = forms.BooleanField(required=False)
174

    
175
    def __init__(self, *args, **kwargs):
176
        self.service = kwargs.pop('service', None)
177
        super(YearlyHolidayForm, self).__init__(*args, **kwargs)
178
        if self.instance and self.instance.id:
179
            self.initial['for_all_services'] = self.instance.service is None
180

    
181

    
182
    def save(self, commit=True):
183
        instance = super(YearlyHolidayForm, self).save(commit=False)
184
        if not self.cleaned_data.get('for_all_services', False):
185
            instance.service = self.service
186
        if commit:
187
            instance.save()
188
        return instance
189

    
190
    class Meta:
191
        form = Holiday
192

    
193
YearlyHolidayFormSet = modelformset_factory(Holiday,
194
        can_delete=True,
195
        form=YearlyHolidayForm,
196
        formset=YearlyHolidayBaseFormSet,
197
        fields=('start_date', 'end_date'))
(3-3/7)