~lutostag/ubuntu/utopic/maas/1.5.2

« back to all changes in this revision

Viewing changes to src/maasserver/forms.py

  • Committer: Package Import Robot
  • Author(s): Andres Rodriguez
  • Date: 2012-03-07 12:46:17 UTC
  • mto: (20.1.1 quantal) (1.2.1)
  • mto: This revision was merged to the branch mainline in revision 4.
  • Revision ID: package-import@ubuntu.com-20120307124617-tdctc6l9bur4f2ci
Tags: upstream-0.1+bzr232+dfsg
ImportĀ upstreamĀ versionĀ 0.1+bzr232+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
10
10
 
11
11
__metaclass__ = type
12
12
__all__ = [
 
13
    "CommissioningForm",
 
14
    "HostnameFormField",
13
15
    "NodeForm",
14
16
    "MACAddressForm",
 
17
    "MaaSAndNetworkForm",
 
18
    "UbuntuForm",
15
19
    ]
16
20
 
17
21
from django import forms
20
24
    UserCreationForm,
21
25
    )
22
26
from django.contrib.auth.models import User
 
27
from django.core.exceptions import ValidationError
 
28
from django.core.validators import URLValidator
23
29
from django.forms import (
 
30
    CharField,
24
31
    Form,
25
32
    ModelForm,
26
33
    )
27
34
from maasserver.fields import MACAddressFormField
28
35
from maasserver.models import (
 
36
    ARCHITECTURE_CHOICES,
29
37
    Config,
30
38
    MACAddress,
31
39
    Node,
34
42
    )
35
43
 
36
44
 
 
45
INVALID_ARCHITECTURE_MESSAGE = (
 
46
    "%(value)s is not a valid architecture. " +
 
47
    "It should be one of: %s." % ", ".join(
 
48
        name for name, value in ARCHITECTURE_CHOICES))
 
49
 
 
50
 
37
51
class NodeForm(ModelForm):
38
52
    system_id = forms.CharField(
39
53
        widget=forms.TextInput(attrs={'readonly': 'readonly'}),
41
55
    after_commissioning_action = forms.TypedChoiceField(
42
56
        choices=NODE_AFTER_COMMISSIONING_ACTION_CHOICES, required=False,
43
57
        empty_value=NODE_AFTER_COMMISSIONING_ACTION.DEFAULT)
 
58
    architecture = forms.ChoiceField(
 
59
        choices=ARCHITECTURE_CHOICES, required=False,
 
60
        error_messages={'invalid_choice': INVALID_ARCHITECTURE_MESSAGE})
44
61
 
45
62
    class Meta:
46
63
        model = Node
47
 
        fields = ('hostname', 'system_id', 'after_commissioning_action')
48
 
 
49
 
 
50
 
class MACAddressForm(ModelForm):
51
 
    class Meta:
52
 
        model = MACAddress
 
64
        fields = (
 
65
            'hostname', 'system_id', 'after_commissioning_action',
 
66
            'architecture')
53
67
 
54
68
 
55
69
class MACAddressForm(ModelForm):
59
73
 
60
74
class MultipleMACAddressField(forms.MultiValueField):
61
75
    def __init__(self, nb_macs=1, *args, **kwargs):
62
 
        fields = [MACAddressFormField() for i in xrange(nb_macs)]
 
76
        fields = [MACAddressFormField() for i in range(nb_macs)]
63
77
        super(MultipleMACAddressField, self).__init__(fields, *args, **kwargs)
64
78
 
65
79
    def compress(self, data_list):
97
111
 
98
112
 
99
113
class ProfileForm(ModelForm):
 
114
    # We use the field 'last_name' to store the user's full name (and
 
115
    # don't display Django's 'first_name' field).
 
116
    last_name = forms.CharField(
 
117
        label="Full name", max_length=30, required=False)
 
118
 
100
119
    class Meta:
101
120
        model = User
102
 
        fields = ('first_name', 'last_name', 'email')
 
121
        fields = ('last_name', 'email')
103
122
 
104
123
 
105
124
class NewUserCreationForm(UserCreationForm):
106
 
    # Add is_superuser field.
107
125
    is_superuser = forms.BooleanField(
108
 
        label="Administrator status", required=False)
 
126
        label="MaaS administrator", required=False)
 
127
 
 
128
    def __init__(self, *args, **kwargs):
 
129
        super(NewUserCreationForm, self).__init__(*args, **kwargs)
 
130
        # Insert 'last_name' field at the right place (right after
 
131
        # the 'username' field).
 
132
        self.fields.insert(
 
133
            1, 'last_name',
 
134
            forms.CharField(label="Full name", max_length=30, required=False))
 
135
        # Insert 'email' field at the right place (right after
 
136
        # the 'last_name' field).
 
137
        self.fields.insert(
 
138
            2, 'email',
 
139
            forms.EmailField(
 
140
                label="E-mail address", max_length=75, required=False))
109
141
 
110
142
    def save(self, commit=True):
111
143
        user = super(NewUserCreationForm, self).save(commit=False)
112
144
        if self.cleaned_data.get('is_superuser', False):
113
145
            user.is_superuser = True
 
146
        new_last_name = self.cleaned_data.get('last_name', None)
 
147
        if new_last_name is not None:
 
148
            user.last_name = new_last_name
 
149
        new_email = self.cleaned_data.get('email', None)
 
150
        if new_email is not None:
 
151
            user.email = new_email
114
152
        user.save()
115
153
        return user
116
154
 
118
156
class EditUserForm(UserChangeForm):
119
157
    # Override the default label.
120
158
    is_superuser = forms.BooleanField(
121
 
        label="Administrator status", required=False)
 
159
        label="MaaS administrator", required=False)
 
160
    last_name = forms.CharField(
 
161
        label="Full name", max_length=30, required=False)
122
162
 
123
163
    class Meta:
124
164
        model = User
125
165
        fields = (
126
 
            'username', 'first_name', 'last_name', 'email', 'is_superuser')
 
166
            'username', 'last_name', 'email', 'is_superuser')
127
167
 
128
168
 
129
169
class ConfigForm(Form):
134
174
    def __init__(self, *args, **kwargs):
135
175
        super(ConfigForm, self).__init__(*args, **kwargs)
136
176
        if 'initial' not in kwargs:
137
 
            configs = Config.objects.filter(name__in=list(self.fields))
138
 
            self.initial = {config.name: config.value for config in configs}
 
177
            self._load_initials()
 
178
 
 
179
    def _load_initials(self):
 
180
        self.initial = {}
 
181
        for name in self.fields.keys():
 
182
            conf = Config.objects.get_config(name)
 
183
            if conf is not None:
 
184
                self.initial[name] = conf
139
185
 
140
186
    def save(self):
141
187
        """Save the content of the fields into the database.
151
197
            for name, value in self.cleaned_data.items():
152
198
                Config.objects.set_config(name, value)
153
199
            return True
 
200
 
 
201
 
 
202
class MaaSAndNetworkForm(ConfigForm):
 
203
    """Settings page, MaaS and Network section."""
 
204
    maas_name = forms.CharField(label="MaaS name")
 
205
    provide_dhcp = forms.BooleanField(
 
206
        label="Provide DHCP on this subnet", required=False)
 
207
 
 
208
 
 
209
class CommissioningForm(ConfigForm):
 
210
    """Settings page, CommissioningF section."""
 
211
    check_compatibility = forms.BooleanField(
 
212
        label="Check component compatibility and certification",
 
213
        required=False)
 
214
    after_commissioning = forms.ChoiceField(
 
215
        choices=NODE_AFTER_COMMISSIONING_ACTION_CHOICES,
 
216
        label="After commissioning")
 
217
 
 
218
 
 
219
class UbuntuForm(ConfigForm):
 
220
    """Settings page, Ubuntu section."""
 
221
    fallback_master_archive = forms.BooleanField(
 
222
        label="Fallback to Ubuntu master archive",
 
223
        required=False)
 
224
    keep_mirror_list_uptodate = forms.BooleanField(
 
225
        label="Keep mirror list up to date",
 
226
        required=False)
 
227
    fetch_new_releases = forms.BooleanField(
 
228
        label="Fetch new releases automatically",
 
229
        required=False)
 
230
 
 
231
    def __init__(self, *args, **kwargs):
 
232
        super(UbuntuForm, self).__init__(*args, **kwargs)
 
233
        # The field 'update_from' must be added dynamically because its
 
234
        # 'choices' must be evaluated each time the form is instantiated.
 
235
        self.fields['update_from'] = forms.ChoiceField(
 
236
            label="Update from",
 
237
            choices=Config.objects.get_config('update_from_choice'))
 
238
        # The list of fields has changed: load initial values.
 
239
        self._load_initials()
 
240
 
 
241
 
 
242
hostname_error_msg = "Enter a valid hostname (e.g. host.example.com)."
 
243
 
 
244
 
 
245
def validate_hostname(value):
 
246
    try:
 
247
        validator = URLValidator(verify_exists=False)
 
248
        validator('http://%s' % value)
 
249
    except ValidationError:
 
250
        raise ValidationError(hostname_error_msg)
 
251
 
 
252
 
 
253
class HostnameFormField(CharField):
 
254
 
 
255
    def __init__(self, *args, **kwargs):
 
256
        super(HostnameFormField, self).__init__(
 
257
            validators=[validate_hostname], *args, **kwargs)
 
258
 
 
259
 
 
260
class AddArchiveForm(ConfigForm):
 
261
    archive_name = HostnameFormField(label="Archive name")
 
262
 
 
263
    def save(self):
 
264
        """Save the archive name in the Config table."""
 
265
        archive_name = self.cleaned_data.get('archive_name')
 
266
        archives = Config.objects.get_config('update_from_choice')
 
267
        archives.append([archive_name, archive_name])
 
268
        Config.objects.set_config('update_from_choice', archives)