Ce serveur Gitlab sera éteint le 30 juin 2020, pensez à migrer vos projets vers les serveurs gitlab-research.centralesupelec.fr et gitlab-student.centralesupelec.fr !

forms.py 8.92 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 est 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 25 26 27 28 29 30 31
"""
Un forms le plus simple possible pour les objets topologie de re2o.

Permet de créer et supprimer : un Port de switch, relié à un switch.

Permet de créer des stacks et d'y ajouter des switchs (StackForm)

Permet de créer, supprimer et editer un switch (EditSwitchForm,
NewSwitchForm)
"""
32

33 34
from __future__ import unicode_literals

35 36 37
from django import forms
from django.forms import ModelForm
from django.db.models import Prefetch
Fernet Laouen's avatar
Fernet Laouen committed
38
from django.utils.translation import ugettext_lazy as _
39

40
from machines.models import Interface
41 42 43 44
from machines.forms import (
    EditMachineForm,
    NewMachineForm
)
45 46
from re2o.mixins import FormRevMixin

47
from .models import (
48 49 50 51 52 53
    Port,
    Switch,
    Room,
    Stack,
    ModelSwitch,
    ConstructorSwitch,
54 55 56
    AccessPoint,
    SwitchBay,
    Building,
Fernet Laouen's avatar
Fernet Laouen committed
57
    PortProfile,
58
)
59

60

61
class PortForm(FormRevMixin, ModelForm):
62 63
    """Formulaire pour la création d'un port d'un switch
    Relié directement au modèle port"""
Dalahro's avatar
Dalahro committed
64 65 66 67
    class Meta:
        model = Port
        fields = '__all__'

68
    def __init__(self, *args, **kwargs):
69
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
70 71
        super(PortForm, self).__init__(*args, prefix=prefix, **kwargs)

72

73
class EditPortForm(FormRevMixin, ModelForm):
74 75 76 77 78 79 80 81
    """Form pour l'édition d'un port de switche : changement des reglages
    radius ou vlan, ou attribution d'une chambre, autre port ou machine

    Un port est relié à une chambre, un autre port (uplink) ou une machine
    (serveur ou borne), mutuellement exclusif
    Optimisation sur les queryset pour machines et port_related pour
    optimiser le temps de chargement avec select_related (vraiment
    lent sans)"""
Dalahro's avatar
Dalahro committed
82
    class Meta(PortForm.Meta):
83 84
        fields = ['room', 'related', 'machine_interface', 'custom_profile',
                  'state', 'details']
Dalahro's avatar
Dalahro committed
85

86
    def __init__(self, *args, **kwargs):
87
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
88
        super(EditPortForm, self).__init__(*args, prefix=prefix, **kwargs)
89 90 91 92 93
        self.fields['machine_interface'].queryset = (
            Interface.objects.all().select_related('domain__extension')
        )
        self.fields['related'].queryset = (
            Port.objects.all()
94
            .prefetch_related(Prefetch(
95 96 97 98
                'switch__interface_set',
                queryset=(Interface.objects
                          .select_related('ipv4__ip_type__extension')
                          .select_related('domain__extension'))
99
            ))
100
        )
101

102

103
class AddPortForm(FormRevMixin, ModelForm):
104 105
    """Permet d'ajouter un port de switch. Voir EditPortForm pour plus
    d'informations"""
Dalahro's avatar
Dalahro committed
106
    class Meta(PortForm.Meta):
107 108 109 110 111
        fields = [
            'port',
            'room',
            'machine_interface',
            'related',
112
            'custom_profile',
113
            'state',
114 115
            'details'
        ]
Dalahro's avatar
Dalahro committed
116

117
    def __init__(self, *args, **kwargs):
118
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
119
        super(AddPortForm, self).__init__(*args, prefix=prefix, **kwargs)
120 121 122 123 124 125 126 127 128
        self.fields['machine_interface'].queryset = (
            Interface.objects.all().select_related('domain__extension')
        )
        self.fields['related'].queryset = (
            Port.objects.all().prefetch_related(Prefetch(
                'switch__interface_set',
                queryset=(Interface.objects
                          .select_related('ipv4__ip_type__extension')
                          .select_related('domain__extension'))
129
            ))
130
        )
131

132

133
class StackForm(FormRevMixin, ModelForm):
134 135
    """Permet d'edition d'une stack : stack_id, et switches membres
    de la stack"""
136 137 138 139
    class Meta:
        model = Stack
        fields = '__all__'

140
    def __init__(self, *args, **kwargs):
141
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
142 143
        super(StackForm, self).__init__(*args, prefix=prefix, **kwargs)

144

145
class AddAccessPointForm(NewMachineForm):
146 147 148
    """Formulaire pour la création d'une borne
    Relié directement au modèle borne"""
    class Meta:
149
        model = AccessPoint
150
        fields = ['location', 'name']
151 152


153 154
class EditAccessPointForm(EditMachineForm):
    """Edition d'une borne. Edition complète"""
155
    class Meta:
156
        model = AccessPoint
157
        fields = '__all__'
158 159


160
class EditSwitchForm(EditMachineForm):
161
    """Permet d'éditer un switch : nom et nombre de ports"""
Dalahro's avatar
Dalahro committed
162 163
    class Meta:
        model = Switch
164
        fields = '__all__'
Dalahro's avatar
Dalahro committed
165

166

167
class NewSwitchForm(NewMachineForm):
168 169
    """Permet de créer un switch : emplacement, paramètres machine,
    membre d'un stack (option), nombre de ports (number)"""
chirac's avatar
chirac committed
170
    class Meta(EditSwitchForm.Meta):
171
        fields = ['name', 'switchbay', 'number', 'stack', 'stack_member_id']
Dalahro's avatar
Dalahro committed
172

173

174
class EditRoomForm(FormRevMixin, ModelForm):
175
    """Permet d'éediter le nom et commentaire d'une prise murale"""
chirac's avatar
chirac committed
176 177 178
    class Meta:
        model = Room
        fields = '__all__'
179

180
    def __init__(self, *args, **kwargs):
181
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
182
        super(EditRoomForm, self).__init__(*args, prefix=prefix, **kwargs)
183 184


185
class CreatePortsForm(forms.Form):
186 187 188 189 190
    """Permet de créer une liste de ports pour un switch."""
    begin = forms.IntegerField(label="Début :", min_value=0)
    end = forms.IntegerField(label="Fin :", min_value=0)


191
class EditModelSwitchForm(FormRevMixin, ModelForm):
192
    """Permet d'éediter un modèle de switch : nom et constructeur"""
193 194 195 196 197
    members = forms.ModelMultipleChoiceField(
        Switch.objects.all(),
        required=False
    )

198 199 200 201 202 203
    class Meta:
        model = ModelSwitch
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
204 205 206 207 208
        super(EditModelSwitchForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
209 210 211 212 213 214 215 216
        instance = kwargs.get('instance', None)
        if instance:
            self.initial['members'] = Switch.objects.filter(model=instance)

    def save(self, commit=True):
        instance = super().save(commit)
        instance.switch_set = self.cleaned_data['members']
        return instance
217 218


219
class EditConstructorSwitchForm(FormRevMixin, ModelForm):
220 221 222 223 224 225 226
    """Permet d'éediter le nom d'un constructeur"""
    class Meta:
        model = ConstructorSwitch
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
227 228 229 230 231
        super(EditConstructorSwitchForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
232 233 234 235


class EditSwitchBayForm(FormRevMixin, ModelForm):
    """Permet d'éditer une baie de brassage"""
236 237 238 239 240
    members = forms.ModelMultipleChoiceField(
        Switch.objects.all(),
        required=False
    )

241 242 243 244 245 246 247
    class Meta:
        model = SwitchBay
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(EditSwitchBayForm, self).__init__(*args, prefix=prefix, **kwargs)
248 249 250 251 252 253 254 255
        instance = kwargs.get('instance', None)
        if instance:
            self.initial['members'] = Switch.objects.filter(switchbay=instance)

    def save(self, commit=True):
        instance = super().save(commit)
        instance.switch_set = self.cleaned_data['members']
        return instance
256 257 258 259 260 261 262 263 264 265 266


class EditBuildingForm(FormRevMixin, ModelForm):
    """Permet d'éditer le batiment"""
    class Meta:
        model = Building
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(EditBuildingForm, self).__init__(*args, prefix=prefix, **kwargs)
Fernet Laouen's avatar
Fernet Laouen committed
267 268 269 270 271 272 273 274 275 276 277 278 279

class EditPortProfileForm(FormRevMixin, ModelForm):
    """Form to edit a port profile"""
    class Meta:
        model = PortProfile
        fields = '__all__'

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