forms.py 8.03 KB
Newer Older
Jeremy Kerr's avatar
Jeremy Kerr committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Patchwork - automated patch tracking system
# Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
#
# This file is part of the Patchwork package.
#
# Patchwork is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Patchwork 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Patchwork; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


from django.contrib.auth.models import User
Jeremy Kerr's avatar
Jeremy Kerr committed
22
from django import forms
Jeremy Kerr's avatar
Jeremy Kerr committed
23

24
25
26
from patchwork.models import Patch, State, Bundle, UserProfile
from registration.forms import RegistrationFormUniqueEmail
from registration.models import RegistrationProfile
Jeremy Kerr's avatar
Jeremy Kerr committed
27

28
29
30
31
32
33
34
35
36
class RegistrationForm(RegistrationFormUniqueEmail):
    first_name = forms.CharField(max_length = 30, required = False)
    last_name = forms.CharField(max_length = 30, required = False)
    username = forms.CharField(max_length=30, label=u'Username')
    email = forms.EmailField(max_length=100, label=u'Email address')
    password = forms.CharField(widget=forms.PasswordInput(),
                                label='Password')
    password1 = forms.BooleanField(required = False)
    password2 = forms.BooleanField(required = False)
Jeremy Kerr's avatar
Jeremy Kerr committed
37

38
39
40
41
42
43
44
45
46
    def save(self, profile_callback = None):
        user = RegistrationProfile.objects.create_inactive_user( \
                username = self.cleaned_data['username'],
                password = self.cleaned_data['password'],
                email = self.cleaned_data['email'],
                profile_callback = profile_callback)
        user.first_name = self.cleaned_data.get('first_name', '')
        user.last_name = self.cleaned_data.get('last_name', '')
        user.save()
47
48
49
50
51

	# saving the userprofile causes the firstname/lastname to propagate
	# to the person objects.
	user.get_profile().save()

52
        return user
Jeremy Kerr's avatar
Jeremy Kerr committed
53

54
55
    def clean(self):
        return self.cleaned_data
Jeremy Kerr's avatar
Jeremy Kerr committed
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

class LoginForm(forms.Form):
    username = forms.CharField(max_length = 30)
    password = forms.CharField(widget = forms.PasswordInput)

class BundleForm(forms.ModelForm):
    class Meta:
        model = Bundle
        fields = ['name', 'public']

class CreateBundleForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CreateBundleForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Bundle
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        count = Bundle.objects.filter(owner = self.instance.owner, \
                name = name).count()
        if count > 0:
            raise forms.ValidationError('A bundle called %s already exists' \
                    % name)
        return name

83
84
85
86
87
class DeleteBundleForm(forms.Form):
    name = 'deletebundleform'
    form_name = forms.CharField(initial = name, widget = forms.HiddenInput)
    bundle_id = forms.IntegerField(widget = forms.HiddenInput)

Jeremy Kerr's avatar
Jeremy Kerr committed
88
89
class DelegateField(forms.ModelChoiceField):
    def __init__(self, project, *args, **kwargs):
90
        queryset = User.objects.filter(userprofile__in = \
Jeremy Kerr's avatar
Jeremy Kerr committed
91
92
93
94
95
96
97
98
                UserProfile.objects \
                        .filter(maintainer_projects = project) \
                        .values('pk').query)
        super(DelegateField, self).__init__(queryset, *args, **kwargs)


class PatchForm(forms.ModelForm):
    def __init__(self, instance = None, project = None, *args, **kwargs):
99
        if (not project) and instance:
Jeremy Kerr's avatar
Jeremy Kerr committed
100
101
            project = instance.project
        if not project:
102
            raise Exception("meep")
Jeremy Kerr's avatar
Jeremy Kerr committed
103
        super(PatchForm, self).__init__(instance = instance, *args, **kwargs)
104
        self.fields['delegate'] = DelegateField(project, required = False)
Jeremy Kerr's avatar
Jeremy Kerr committed
105
106
107
108
109
110
111
112
113
114
115
116

    class Meta:
        model = Patch
        fields = ['state', 'archived', 'delegate']

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['primary_project', 'patches_per_page']

class OptionalDelegateField(DelegateField):
    no_change_choice = ('*', 'no change')
117
    to_field_name = None
Jeremy Kerr's avatar
Jeremy Kerr committed
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

    def __init__(self, no_change_choice = None, *args, **kwargs):
        self.filter = None
        if (no_change_choice):
            self.no_change_choice = no_change_choice
        super(OptionalDelegateField, self). \
            __init__(initial = self.no_change_choice[0], *args, **kwargs)

    def _get_choices(self):
        choices = list(
                super(OptionalDelegateField, self)._get_choices())
        choices.append(self.no_change_choice)
        return choices

    choices = property(_get_choices, forms.ChoiceField._set_choices)

    def is_no_change(self, value):
        return value == self.no_change_choice[0]

    def clean(self, value):
        if value == self.no_change_choice[0]:
            return value
        return super(OptionalDelegateField, self).clean(value)

class OptionalModelChoiceField(forms.ModelChoiceField):
    no_change_choice = ('*', 'no change')
Jeremy Kerr's avatar
Jeremy Kerr committed
144
    to_field_name = None
Jeremy Kerr's avatar
Jeremy Kerr committed
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

    def __init__(self, no_change_choice = None, *args, **kwargs):
        self.filter = None
        if (no_change_choice):
            self.no_change_choice = no_change_choice
        super(OptionalModelChoiceField, self). \
            __init__(initial = self.no_change_choice[0], *args, **kwargs)

    def _get_choices(self):
        choices = list(
                super(OptionalModelChoiceField, self)._get_choices())
        choices.append(self.no_change_choice)
        return choices

    choices = property(_get_choices, forms.ChoiceField._set_choices)

    def is_no_change(self, value):
        return value == self.no_change_choice[0]

    def clean(self, value):
        if value == self.no_change_choice[0]:
            return value
        return super(OptionalModelChoiceField, self).clean(value)

class MultipleBooleanField(forms.ChoiceField):
    no_change_choice = ('*', 'no change')
    def __init__(self, *args, **kwargs):
        super(MultipleBooleanField, self).__init__(*args, **kwargs)
        self.choices = [self.no_change_choice] + \
                [(True, 'Archived'), (False, 'Unarchived')]

    def is_no_change(self, value):
        return value == self.no_change_choice[0]

class MultiplePatchForm(PatchForm):
    state = OptionalModelChoiceField(queryset = State.objects.all())
    archived = MultipleBooleanField()

    def __init__(self, project, *args, **kwargs):
        super(MultiplePatchForm, self).__init__(project = project,
                *args, **kwargs)
186
        self.fields['delegate'] = OptionalDelegateField(project = project,
187
                required = False)
Jeremy Kerr's avatar
Jeremy Kerr committed
188

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    def _clean_fields(self):
        super(MultiplePatchForm, self)._clean_fields()
        # remove optional fields
        opts = self.instance._meta
        for f in opts.fields:
            if not f.name in self.cleaned_data:
                continue

            field = self.fields.get(f.name, None)
            if field is None:
                continue

            if field.is_no_change(self.cleaned_data[f.name]):
                del self.cleaned_data[f.name]

Jeremy Kerr's avatar
Jeremy Kerr committed
204
205
206
207
208
209
210
211
212
213
214
    def save(self, instance, commit = True):
        opts = instance.__class__._meta
        if self.errors:
            raise ValueError("The %s could not be changed because the data "
                    "didn't validate." % opts.object_name)
        data = self.cleaned_data
        # remove 'no change fields' from the data
        for f in opts.fields:
            if not f.name in data:
                continue

215
            field = self.fields.get(f.name, None)
Jeremy Kerr's avatar
Jeremy Kerr committed
216
217
218
219
220
221
222
223
224
225
226
            if not field:
                continue

            if field.is_no_change(data[f.name]):
                del data[f.name]

        return forms.save_instance(self, instance,
                self._meta.fields, 'changed', commit)

class UserPersonLinkForm(forms.Form):
    email = forms.EmailField(max_length = 200)