forms.py 14.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Re2o un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2017  Gabriel Détraz
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
#
# This program 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.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 23 24
"""
Formulaire d'edition des réglages : user, machine, topologie, asso...
"""
25

26 27
from __future__ import unicode_literals

28
from django.forms import ModelForm, Form
29
from django import forms
30
from django.utils.translation import ugettext_lazy as _
31
from re2o.mixins import FormRevMixin
Gabriel Detraz's avatar
Gabriel Detraz committed
32 33 34 35 36 37 38
from .models import (
    OptionalUser,
    OptionalMachine,
    OptionalTopologie,
    GeneralOption,
    AssoOption,
    MailMessageOption,
Gabriel Detraz's avatar
Gabriel Detraz committed
39
    HomeOption,
40
    Service,
41
    MailContact,
42
    Reminder,
43
    RadiusKey,
44
    SwitchManagementCred,
Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
45
    RadiusOption,
46 47
    CotisationsOption,
    DocumentTemplate
Gabriel Detraz's avatar
Gabriel Detraz committed
48
)
49
from topologie.models import Switch
50

51

52
class EditOptionalUserForm(ModelForm):
53
    """Formulaire d'édition des options de l'user. (solde, telephone..)"""
54 55 56 57 58
    class Meta:
        model = OptionalUser
        fields = '__all__'

    def __init__(self, *args, **kwargs):
59
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
60 61 62 63 64
        super(EditOptionalUserForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
Maël Kervella's avatar
Maël Kervella committed
65
        self.fields['is_tel_mandatory'].label = (
66
            _("Telephone number required")
Maël Kervella's avatar
Maël Kervella committed
67
        )
68 69 70 71 72
        self.fields['gpg_fingerprint'].label = _("GPG fingerprint")
        self.fields['all_can_create_club'].label = _("All can create a club")
        self.fields['all_can_create_adherent'].label = _("All can create a member")
        self.fields['self_adhesion'].label = _("Self registration")
        self.fields['shell_default'].label = _("Default shell")
73

74

75
class EditOptionalMachineForm(ModelForm):
76
    """Options machines (max de machines, etc)"""
77 78 79 80 81
    class Meta:
        model = OptionalMachine
        fields = '__all__'

    def __init__(self, *args, **kwargs):
82
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
83 84 85 86 87
        super(EditOptionalMachineForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
88 89 90 91 92 93 94 95 96 97 98
        self.fields['password_machine'].label = _("Possibility to set a"
                                                  " password per machine")
        self.fields['max_lambdauser_interfaces'].label = _("Maximum number of"
                                                           " interfaces"
                                                           " allowed for a"
                                                           " standard user")
        self.fields['max_lambdauser_aliases'].label = _("Maximum number of DNS"
                                                        " aliases allowed for"
                                                        " a standard user")
        self.fields['ipv6_mode'].label = _("IPv6 mode")
        self.fields['create_machine'].label = _("Can create a machine")
99

100

101
class EditOptionalTopologieForm(ModelForm):
102 103 104 105 106 107 108 109
    """Options de topologie, formulaire d'edition (vlan par default etc)
    On rajoute un champ automatic provision switchs pour gérer facilement
    l'ajout de switchs au provisionning automatique"""
    automatic_provision_switchs = forms.ModelMultipleChoiceField(
        Switch.objects.all(),
        required=False
    )

110 111 112 113 114
    class Meta:
        model = OptionalTopologie
        fields = '__all__'

    def __init__(self, *args, **kwargs):
115
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
116 117 118 119 120 121
        super(EditOptionalTopologieForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )

122
        self.initial['automatic_provision_switchs'] = Switch.objects.filter(automatic_provision=True).order_by('interface__domain__name')
123 124 125 126 127 128 129

    def save(self, commit=True):
        instance = super().save(commit)
        Switch.objects.all().update(automatic_provision=False)
        self.cleaned_data['automatic_provision_switchs'].update(automatic_provision=True)
        return instance

130

131
class EditGeneralOptionForm(ModelForm):
132
    """Options générales (affichages de résultats de recherche, etc)"""
133 134 135 136 137
    class Meta:
        model = GeneralOption
        fields = '__all__'

    def __init__(self, *args, **kwargs):
138
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
139 140 141 142 143
        super(EditGeneralOptionForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
144 145
        self.fields['general_message_fr'].label = _("General message in French")
        self.fields['general_message_en'].label = _("General message in English")
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        self.fields['search_display_page'].label = _("Number of results"
                                                     " displayed when"
                                                     " searching")
        self.fields['pagination_number'].label = _("Number of items per page,"
                                                   " standard size (e.g."
                                                   " users)")
        self.fields['pagination_large_number'].label = _("Number of items per"
                                                         " page, large size"
                                                         " (e.g. machines)")
        self.fields['req_expire_hrs'].label = _("Time before expiration of the"
                                                " reset password link (in"
                                                " hours)")
        self.fields['site_name'].label = _("Website name")
        self.fields['email_from'].label = _("Email address for automatic"
                                            " emailing")
        self.fields['GTU_sum_up'].label = _("Summary of the General Terms of"
                                            " Use")
        self.fields['GTU'].label = _("General Terms of Use")
164

165 166

class EditAssoOptionForm(ModelForm):
167
    """Options de l'asso (addresse, telephone, etc)"""
168 169 170 171
    class Meta:
        model = AssoOption
        fields = '__all__'

172
    def __init__(self, *args, **kwargs):
173
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
174 175 176 177 178
        super(EditAssoOptionForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
179 180 181 182 183 184 185 186 187 188
        self.fields['name'].label = _("Organisation name")
        self.fields['siret'].label = _("SIRET number")
        self.fields['adresse1'].label = _("Address (line 1)")
        self.fields['adresse2'].label = _("Address (line 2)")
        self.fields['contact'].label = _("Contact email address")
        self.fields['telephone'].label = _("Telephone number")
        self.fields['pseudo'].label = _("Usual name")
        self.fields['utilisateur_asso'].label = _("Account used for editing"
                                                  " from /admin")
        self.fields['description'].label = _("Description")
189

190

191
class EditMailMessageOptionForm(ModelForm):
192
    """Formulaire d'edition des messages de bienvenue personnalisés"""
193 194 195 196
    class Meta:
        model = MailMessageOption
        fields = '__all__'

197
    def __init__(self, *args, **kwargs):
198
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
199 200 201 202 203
        super(EditMailMessageOptionForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
204 205 206 207
        self.fields['welcome_mail_fr'].label = _("Message for the French"
                                                 " welcome email")
        self.fields['welcome_mail_en'].label = _("Message for the English"
                                                 " welcome email")
208

209

Gabriel Detraz's avatar
Gabriel Detraz committed
210 211
class EditHomeOptionForm(ModelForm):
    """Edition forms of Home options"""
Gabriel Detraz's avatar
Gabriel Detraz committed
212
    class Meta:
Gabriel Detraz's avatar
Gabriel Detraz committed
213
        model = HomeOption
Gabriel Detraz's avatar
Gabriel Detraz committed
214 215 216 217
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
Gabriel Detraz's avatar
Gabriel Detraz committed
218
        super(EditHomeOptionForm, self).__init__(
Gabriel Detraz's avatar
Gabriel Detraz committed
219 220 221 222
            *args,
            prefix=prefix,
            **kwargs
        )
223 224 225
        self.fields['facebook_url'].label = _("Facebook URL")
        self.fields['twitter_url'].label = _("Twitter URL")
        self.fields['twitter_account_name'].label = _("Twitter account name")
Gabriel Detraz's avatar
Gabriel Detraz committed
226 227


Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
228 229 230 231
class EditRadiusOptionForm(ModelForm):
    """Edition forms for Radius options"""
    class Meta:
        model = RadiusOption
232
        fields = '__all__'
Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
233

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    def clean(self):
        cleaned_data = super().clean()
        ignored=('radius_general_policy', 'vlan_decision_ok')
        fields = (
            f for f in self.fields.keys()
            if 'vlan' not in f and f not in ignored
        )
        for f in fields:
            choice = cleaned_data.get(f)
            vlan = cleaned_data.get(f+'_vlan')
            if choice == RadiusOption.SET_VLAN and vlan is None:
                self.add_error(
                    f,
                    _("You chose to set vlan but did not set any VLAN."),
                )
                self.add_error(
                    f+'_vlan',
                    _("Please, choose a VLAN."),
                )
        return cleaned_data

Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
255

256 257 258 259 260 261 262
class EditCotisationsOptionForm(ModelForm):
    """Edition forms for Cotisations options"""
    class Meta:
        model = CotisationsOption
        fields = '__all__'


263
class ServiceForm(ModelForm):
264
    """Edition, ajout de services sur la page d'accueil"""
265 266 267
    class Meta:
        model = Service
        fields = '__all__'
268

269
    def __init__(self, *args, **kwargs):
270
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
271
        super(ServiceForm, self).__init__(*args, prefix=prefix, **kwargs)
272 273 274 275
        self.fields['name'].label = _("Name")
        self.fields['url'].label = _("URL")
        self.fields['description'].label = _("Description")
        self.fields['image'].label = _("Image")
276 277


278 279 280
class DelServiceForm(Form):
    """Suppression de services sur la page d'accueil"""
    services = forms.ModelMultipleChoiceField(
281
        queryset=Service.objects.none(),
282
        label=_("Current services"),
283 284
        widget=forms.CheckboxSelectMultiple
    )
285 286 287 288 289 290 291 292

    def __init__(self, *args, **kwargs):
        instances = kwargs.pop('instances', None)
        super(DelServiceForm, self).__init__(*args, **kwargs)
        if instances:
            self.fields['services'].queryset = instances
        else:
            self.fields['services'].queryset = Service.objects.all()
293

294 295 296 297 298 299 300 301 302 303
class ReminderForm(FormRevMixin, ModelForm):
    """Edition, ajout de services sur la page d'accueil"""
    class Meta:
        model = Reminder
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(ReminderForm, self).__init__(*args, prefix=prefix, **kwargs)

304 305 306 307

class RadiusKeyForm(FormRevMixin, ModelForm):
    """Edition, ajout de clef radius"""
    members = forms.ModelMultipleChoiceField(
308
        queryset=Switch.objects.all(),
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        required=False
    )

    class Meta:
        model = RadiusKey
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(RadiusKeyForm, self).__init__(*args, prefix=prefix, **kwargs)
        instance = kwargs.get('instance', None)
        if instance:
            self.initial['members'] = Switch.objects.filter(radius_key=instance)

    def save(self, commit=True):
        instance = super().save(commit)
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        instance.switch_set = self.cleaned_data['members']
        return instance


class SwitchManagementCredForm(FormRevMixin, ModelForm):
    """Edition, ajout de creds de management pour gestion
    et interface rest des switchs"""
    members = forms.ModelMultipleChoiceField(
        Switch.objects.all(),
        required=False
    )

    class Meta:
        model = SwitchManagementCred
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(SwitchManagementCredForm, self).__init__(*args, prefix=prefix, **kwargs)
        instance = kwargs.get('instance', None)
        if instance:
            self.initial['members'] = Switch.objects.filter(management_creds=instance)

    def save(self, commit=True):
        instance = super().save(commit)
350 351 352 353 354 355
        instance.switch_set = self.cleaned_data['members']
        return instance


class MailContactForm(ModelForm):
    """Edition, ajout d'adresse de contact"""
356 357 358 359 360 361 362 363 364 365
    class Meta:
        model = MailContact
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(MailContactForm, self).__init__(*args, prefix=prefix, **kwargs)


class DelMailContactForm(Form):
366
    """Delete contact email adress"""
367 368
    mailcontacts = forms.ModelMultipleChoiceField(
        queryset=MailContact.objects.none(),
369
        label=_("Current email addresses"),
370 371 372 373 374 375 376 377 378 379
        widget=forms.CheckboxSelectMultiple
    )

    def __init__(self, *args, **kwargs):
        instances = kwargs.pop('instances', None)
        super(DelMailContactForm, self).__init__(*args, **kwargs)
        if instances:
            self.fields['mailcontacts'].queryset = instances
        else:
            self.fields['mailcontacts'].queryset = MailContact.objects.all()
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

class DocumentTemplateForm(FormRevMixin, ModelForm):
    """
    Form used to create a document template.
    """
    class Meta:
        model = DocumentTemplate
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(DocumentTemplateForm, self).__init__(
            *args, prefix=prefix, **kwargs)


class DelDocumentTemplateForm(FormRevMixin, Form):
    """
    Form used to delete one or more document templatess.
    The use must choose the one to delete by checking the boxes.
    """
    document_templates = forms.ModelMultipleChoiceField(
        queryset=DocumentTemplate.objects.none(),
        label=_("Available document templates"),
        widget=forms.CheckboxSelectMultiple
    )

    def __init__(self, *args, **kwargs):
        instances = kwargs.pop('instances', None)
        super(DelDocumentTemplateForm, self).__init__(*args, **kwargs)
        if instances:
            self.fields['document_templates'].queryset = instances
        else:
            self.fields['document_templates'].queryset = Banque.objects.all()