8
0
Fork 0
mirror of https://gitlab2.federez.net/re2o/re2o synced 2024-11-25 22:22:26 +00:00

Doc et respect de la pep8

This commit is contained in:
chirac 2017-10-14 01:43:01 +02:00
parent 9660a3d017
commit dc3096a3bf
3 changed files with 248 additions and 106 deletions

View file

@ -42,6 +42,7 @@ from django.db.models.signals import post_delete
from django.dispatch import receiver from django.dispatch import receiver
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
class Stack(models.Model): class Stack(models.Model):
"""Un objet stack. Regrouppe des switchs en foreign key """Un objet stack. Regrouppe des switchs en foreign key
,contient une id de stack, un switch id min et max dans ,contient une id de stack, un switch id min et max dans
@ -69,6 +70,7 @@ class Stack(models.Model):
raise ValidationError({'member_id_max': "L'id maximale est\ raise ValidationError({'member_id_max': "L'id maximale est\
inférieure à l'id minimale"}) inférieure à l'id minimale"})
class Switch(models.Model): class Switch(models.Model):
""" Definition d'un switch. Contient un nombre de ports (number), """ Definition d'un switch. Contient un nombre de ports (number),
un emplacement (location), un stack parent (optionnel, stack) un emplacement (location), un stack parent (optionnel, stack)
@ -110,12 +112,15 @@ class Switch(models.Model):
if self.stack_member_id is not None: if self.stack_member_id is not None:
if (self.stack_member_id > self.stack.member_id_max) or\ if (self.stack_member_id > self.stack.member_id_max) or\
(self.stack_member_id < self.stack.member_id_min): (self.stack_member_id < self.stack.member_id_min):
raise ValidationError({'stack_member_id': "L'id de ce\ raise ValidationError(
switch est en dehors des bornes permises pas la stack"}) {'stack_member_id': "L'id de ce switch est en\
dehors des bornes permises pas la stack"}
)
else: else:
raise ValidationError({'stack_member_id': "L'id dans la stack\ raise ValidationError({'stack_member_id': "L'id dans la stack\
ne peut être nul"}) ne peut être nul"})
class Port(models.Model): class Port(models.Model):
""" Definition d'un port. Relié à un switch(foreign_key), """ Definition d'un port. Relié à un switch(foreign_key),
un port peut etre relié de manière exclusive à : un port peut etre relié de manière exclusive à :
@ -195,7 +200,8 @@ class Port(models.Model):
cohérence""" cohérence"""
if hasattr(self, 'switch'): if hasattr(self, 'switch'):
if self.port > self.switch.number: if self.port > self.switch.number:
raise ValidationError("Ce port ne peut exister, numero trop élevé") raise ValidationError("Ce port ne peut exister,\
numero trop élevé")
if self.room and self.machine_interface or self.room and\ if self.room and self.machine_interface or self.room and\
self.related or self.machine_interface and self.related: self.related or self.machine_interface and self.related:
raise ValidationError("Chambre, interface et related_port sont\ raise ValidationError("Chambre, interface et related_port sont\
@ -214,6 +220,7 @@ class Port(models.Model):
def __str__(self): def __str__(self):
return str(self.switch) + " - " + str(self.port) return str(self.switch) + " - " + str(self.port)
class Room(models.Model): class Room(models.Model):
"""Une chambre/local contenant une prise murale""" """Une chambre/local contenant une prise murale"""
PRETTY_NAME = "Chambre/ Prise murale" PRETTY_NAME = "Chambre/ Prise murale"
@ -227,6 +234,7 @@ class Room(models.Model):
def __str__(self): def __str__(self):
return str(self.name) return str(self.name)
@receiver(post_delete, sender=Stack) @receiver(post_delete, sender=Stack)
def stack_post_delete(sender, **kwargs): def stack_post_delete(sender, **kwargs):
"""Vide les id des switches membres d'une stack supprimée""" """Vide les id des switches membres d'une stack supprimée"""

View file

@ -19,6 +19,12 @@
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Definition des urls de l'application topologie.
Inclu dans urls de re2o.
Fait référence aux fonctions du views
"""
from __future__ import unicode_literals from __future__ import unicode_literals
@ -33,18 +39,33 @@ urlpatterns = [
url(r'^new_room/$', views.new_room, name='new-room'), url(r'^new_room/$', views.new_room, name='new-room'),
url(r'^edit_room/(?P<room_id>[0-9]+)$', views.edit_room, name='edit-room'), url(r'^edit_room/(?P<room_id>[0-9]+)$', views.edit_room, name='edit-room'),
url(r'^del_room/(?P<room_id>[0-9]+)$', views.del_room, name='del-room'), url(r'^del_room/(?P<room_id>[0-9]+)$', views.del_room, name='del-room'),
url(r'^switch/(?P<switch_id>[0-9]+)$', views.index_port, name='index-port'), url(r'^switch/(?P<switch_id>[0-9]+)$',
url(r'^history/(?P<object>switch)/(?P<id>[0-9]+)$', views.history, name='history'), views.index_port,
url(r'^history/(?P<object>port)/(?P<id>[0-9]+)$', views.history, name='history'), name='index-port'),
url(r'^history/(?P<object>room)/(?P<id>[0-9]+)$', views.history, name='history'), url(r'^history/(?P<object>switch)/(?P<id>[0-9]+)$',
url(r'^history/(?P<object>stack)/(?P<id>[0-9]+)$', views.history, name='history'), views.history,
name='history'),
url(r'^history/(?P<object>port)/(?P<id>[0-9]+)$',
views.history,
name='history'),
url(r'^history/(?P<object>room)/(?P<id>[0-9]+)$',
views.history,
name='history'),
url(r'^history/(?P<object>stack)/(?P<id>[0-9]+)$',
views.history,
name='history'),
url(r'^edit_port/(?P<port_id>[0-9]+)$', views.edit_port, name='edit-port'), url(r'^edit_port/(?P<port_id>[0-9]+)$', views.edit_port, name='edit-port'),
url(r'^new_port/(?P<switch_id>[0-9]+)$', views.new_port, name='new-port'), url(r'^new_port/(?P<switch_id>[0-9]+)$', views.new_port, name='new-port'),
url(r'^del_port/(?P<port_id>[0-9]+)$', views.del_port, name='del-port'), url(r'^del_port/(?P<port_id>[0-9]+)$', views.del_port, name='del-port'),
url(r'^edit_switch/(?P<switch_id>[0-9]+)$', views.edit_switch, name='edit-switch'), url(r'^edit_switch/(?P<switch_id>[0-9]+)$',
views.edit_switch,
name='edit-switch'),
url(r'^new_stack/$', views.new_stack, name='new-stack'), url(r'^new_stack/$', views.new_stack, name='new-stack'),
url(r'^index_stack/$', views.index_stack, name='index-stack'), url(r'^index_stack/$', views.index_stack, name='index-stack'),
url(r'^edit_stack/(?P<stack_id>[0-9]+)$', views.edit_stack, name='edit-stack'), url(r'^edit_stack/(?P<stack_id>[0-9]+)$',
url(r'^del_stack/(?P<stack_id>[0-9]+)$', views.del_stack, name='del-stack'), views.edit_stack,
name='edit-stack'),
url(r'^del_stack/(?P<stack_id>[0-9]+)$',
views.del_stack,
name='del-stack'),
] ]

View file

@ -19,7 +19,20 @@
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Page des vues de l'application topologie
Permet de créer, modifier et supprimer :
- un port (add_port, edit_port, del_port)
- un switch : les vues d'ajout et d'édition font appel aux forms de creation
de switch, mais aussi aux forms de machines.forms (domain, interface et
machine). Le views les envoie et les save en même temps. TODO : rationaliser
et faire que la creation de machines (interfaces, domain etc) soit gérée
coté models et forms de topologie
- une chambre (new_room, edit_room, del_room)
- une stack
- l'historique de tous les objets cités
"""
from __future__ import unicode_literals from __future__ import unicode_literals
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
@ -33,11 +46,12 @@ from reversion import revisions as reversion
from reversion.models import Version from reversion.models import Version
from topologie.models import Switch, Port, Room, Stack from topologie.models import Switch, Port, Room, Stack
from topologie.forms import EditPortForm, NewSwitchForm, EditSwitchForm, AddPortForm, EditRoomForm, StackForm from topologie.forms import EditPortForm, NewSwitchForm, EditSwitchForm
from topologie.forms import AddPortForm, EditRoomForm, StackForm
from users.views import form from users.views import form
from users.models import User
from machines.forms import AliasForm, NewMachineForm, EditMachineForm, EditInterfaceForm, AddInterfaceForm from machines.forms import AliasForm, NewMachineForm, EditMachineForm
from machines.forms import EditInterfaceForm, AddInterfaceForm
from preferences.models import AssoOption, GeneralOption from preferences.models import AssoOption, GeneralOption
@ -45,41 +59,52 @@ from preferences.models import AssoOption, GeneralOption
@permission_required('cableur') @permission_required('cableur')
def index(request): def index(request):
""" Vue d'affichage de tous les swicthes""" """ Vue d'affichage de tous les swicthes"""
switch_list = Switch.objects.order_by('stack','stack_member_id','location').select_related('switch_interface__domain__extension').select_related('switch_interface__ipv4').select_related('switch_interface__domain').select_related('stack') switch_list = Switch.objects.order_by(
return render(request, 'topologie/index.html', {'switch_list': switch_list}) 'stack',
'stack_member_id',
'location'
)\
.select_related('switch_interface__domain__extension')\
.select_related('switch_interface__ipv4')\
.select_related('switch_interface__domain')\
.select_related('stack')
return render(request, 'topologie/index.html', {
'switch_list': switch_list
})
@login_required @login_required
@permission_required('cableur') @permission_required('cableur')
def history(request, object, id): def history(request, object_name, object_id):
""" Vue générique pour afficher l'historique complet d'un objet""" """ Vue générique pour afficher l'historique complet d'un objet"""
if object == 'switch': if object_name == 'switch':
try: try:
object_instance = Switch.objects.get(pk=id) object_instance = Switch.objects.get(pk=object_id)
except Switch.DoesNotExist: except Switch.DoesNotExist:
messages.error(request, "Switch inexistant") messages.error(request, "Switch inexistant")
return redirect("/topologie/") return redirect("/topologie/")
elif object == 'port': elif object_name == 'port':
try: try:
object_instance = Port.objects.get(pk=id) object_instance = Port.objects.get(pk=object_id)
except Port.DoesNotExist: except Port.DoesNotExist:
messages.error(request, "Port inexistant") messages.error(request, "Port inexistant")
return redirect("/topologie/") return redirect("/topologie/")
elif object == 'room': elif object_name == 'room':
try: try:
object_instance = Room.objects.get(pk=id) object_instance = Room.objects.get(pk=object_id)
except Room.DoesNotExist: except Room.DoesNotExist:
messages.error(request, "Chambre inexistante") messages.error(request, "Chambre inexistante")
return redirect("/topologie/") return redirect("/topologie/")
elif object == 'stack': elif object_name == 'stack':
try: try:
object_instance = Stack.objects.get(pk=id) object_instance = Stack.objects.get(pk=object_id)
except Room.DoesNotExist: except Room.DoesNotExist:
messages.error(request, "Stack inexistante") messages.error(request, "Stack inexistante")
return redirect("/topologie/") return redirect("/topologie/")
else: else:
messages.error(request, "Objet inconnu") messages.error(request, "Objet inconnu")
return redirect("/topologie/") return redirect("/topologie/")
options, created = GeneralOption.objects.get_or_create() options, _created = GeneralOption.objects.get_or_create()
pagination_number = options.pagination_number pagination_number = options.pagination_number
reversions = Version.objects.get_for_object(object_instance) reversions = Version.objects.get_for_object(object_instance)
paginator = Paginator(reversions, pagination_number) paginator = Paginator(reversions, pagination_number)
@ -92,7 +117,11 @@ def history(request, object, id):
except EmptyPage: except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results. # If page is out of range (e.g. 9999), deliver last page of results.
reversions = paginator.page(paginator.num_pages) reversions = paginator.page(paginator.num_pages)
return render(request, 're2o/history.html', {'reversions': reversions, 'object': object_instance}) return render(request, 're2o/history.html', {
'reversions': reversions,
'object': object_instance
})
@login_required @login_required
@permission_required('cableur') @permission_required('cableur')
@ -103,15 +132,25 @@ def index_port(request, switch_id):
except Switch.DoesNotExist: except Switch.DoesNotExist:
messages.error(request, u"Switch inexistant") messages.error(request, u"Switch inexistant")
return redirect("/topologie/") return redirect("/topologie/")
port_list = Port.objects.filter(switch = switch).select_related('room').select_related('machine_interface__domain__extension').select_related('related').select_related('switch').order_by('port') port_list = Port.objects.filter(switch=switch)\
return render(request, 'topologie/index_p.html', {'port_list':port_list, 'id_switch':switch_id, 'nom_switch':switch}) .select_related('room')\
.select_related('machine_interface__domain__extension')\
.select_related('related')\
.select_related('switch')\
.order_by('port')
return render(request, 'topologie/index_p.html', {
'port_list': port_list,
'id_switch': switch_id,
'nom_switch': switch
})
@login_required @login_required
@permission_required('cableur') @permission_required('cableur')
def index_room(request): def index_room(request):
""" Affichage de l'ensemble des chambres""" """ Affichage de l'ensemble des chambres"""
room_list = Room.objects.order_by('name') room_list = Room.objects.order_by('name')
options, created = GeneralOption.objects.get_or_create() options, _created = GeneralOption.objects.get_or_create()
pagination_number = options.pagination_number pagination_number = options.pagination_number
paginator = Paginator(room_list, pagination_number) paginator = Paginator(room_list, pagination_number)
page = request.GET.get('page') page = request.GET.get('page')
@ -123,13 +162,20 @@ def index_room(request):
except EmptyPage: except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results. # If page is out of range (e.g. 9999), deliver last page of results.
room_list = paginator.page(paginator.num_pages) room_list = paginator.page(paginator.num_pages)
return render(request, 'topologie/index_room.html', {'room_list': room_list}) return render(request, 'topologie/index_room.html', {
'room_list': room_list
})
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def index_stack(request): def index_stack(request):
stack_list = Stack.objects.order_by('name').prefetch_related('switch_set__switch_interface__domain__extension') """Affichage de la liste des stacks (affiche l'ensemble des switches)"""
return render(request, 'topologie/index_stack.html', {'stack_list': stack_list}) stack_list = Stack.objects.order_by('name')\
.prefetch_related('switch_set__switch_interface__domain__extension')
return render(request, 'topologie/index_stack.html', {
'stack_list': stack_list
})
@login_required @login_required
@ -156,12 +202,20 @@ def new_port(request, switch_id):
return redirect("/topologie/switch/" + switch_id) return redirect("/topologie/switch/" + switch_id)
return form({'topoform': port}, 'topologie/topo.html', request) return form({'topoform': port}, 'topologie/topo.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def edit_port(request, port_id): def edit_port(request, port_id):
""" Edition d'un port. Permet de changer le switch parent et l'affectation du port""" """ Edition d'un port. Permet de changer le switch parent et
l'affectation du port"""
try: try:
port_object = Port.objects.select_related('switch__switch_interface__domain__extension').select_related('machine_interface__domain__extension').select_related('machine_interface__switch').select_related('room').select_related('related').get(pk=port_id) port_object = Port.objects\
.select_related('switch__switch_interface__domain__extension')\
.select_related('machine_interface__domain__extension')\
.select_related('machine_interface__switch')\
.select_related('room')\
.select_related('related')\
.get(pk=port_id)
except Port.DoesNotExist: except Port.DoesNotExist:
messages.error(request, u"Port inexistant") messages.error(request, u"Port inexistant")
return redirect("/topologie/") return redirect("/topologie/")
@ -170,11 +224,14 @@ def edit_port(request, port_id):
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
port.save() port.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in port.changed_data)) reversion.set_comment("Champs modifié(s) : %s" % ', '.join(
field for field in port.changed_data
))
messages.success(request, "Le port a bien été modifié") messages.success(request, "Le port a bien été modifié")
return redirect("/topologie/switch/" + str(port_object.switch.id)) return redirect("/topologie/switch/" + str(port_object.switch.id))
return form({'topoform': port}, 'topologie/topo.html', request) return form({'topoform': port}, 'topologie/topo.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def del_port(request, port_id): def del_port(request, port_id):
@ -192,30 +249,30 @@ def del_port(request,port_id):
reversion.set_comment("Destruction") reversion.set_comment("Destruction")
messages.success(request, "Le port a eté détruit") messages.success(request, "Le port a eté détruit")
except ProtectedError: except ProtectedError:
messages.error(request, "Le port %s est affecté à un autre objet, impossible de le supprimer" % port) messages.error(request, "Le port %s est affecté à un autre objet,\
impossible de le supprimer" % port)
return redirect('/topologie/switch/' + str(port.switch.id)) return redirect('/topologie/switch/' + str(port.switch.id))
return form({'objet': port}, 'topologie/delete.html', request) return form({'objet': port}, 'topologie/delete.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def new_stack(request): def new_stack(request):
"""Ajoute un nouveau stack : stack_id_min, max, et nombre de switches"""
stack = StackForm(request.POST or None) stack = StackForm(request.POST or None)
#if stack.is_valid(): if stack.is_valid():
if request.POST:
try:
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
stack.save() stack.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Création") reversion.set_comment("Création")
messages.success(request, "Stack crée") messages.success(request, "Stack crée")
except:
messages.error(request, "Cette stack existe déjà")
return form({'topoform': stack}, 'topologie/topo.html', request) return form({'topoform': stack}, 'topologie/topo.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def edit_stack(request, stack_id): def edit_stack(request, stack_id):
"""Edition d'un stack (nombre de switches, nom...)"""
try: try:
stack = Stack.objects.get(pk=stack_id) stack = Stack.objects.get(pk=stack_id)
except Stack.DoesNotExist: except Stack.DoesNotExist:
@ -226,13 +283,19 @@ def edit_stack(request,stack_id):
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
stack.save() stack.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in stack.changed_data)) reversion.set_comment(
"Champs modifié(s) : %s" % ', '.join(
field for field in stack.changed_data
)
)
return redirect('/topologie/index_stack') return redirect('/topologie/index_stack')
return form({'topoform': stack}, 'topologie/topo.html', request) return form({'topoform': stack}, 'topologie/topo.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def del_stack(request, stack_id): def del_stack(request, stack_id):
"""Supprime un stack"""
try: try:
stack = Stack.objects.get(pk=stack_id) stack = Stack.objects.get(pk=stack_id)
except Stack.DoesNotExist: except Stack.DoesNotExist:
@ -246,13 +309,16 @@ def del_stack(request,stack_id):
reversion.set_comment("Destruction") reversion.set_comment("Destruction")
messages.success(request, "La stack a eté détruite") messages.success(request, "La stack a eté détruite")
except ProtectedError: except ProtectedError:
messages.error(request, "La stack %s est affectée à un autre objet, impossible de la supprimer" % stack) messages.error(request, "La stack %s est affectée à un autre\
objet, impossible de la supprimer" % stack)
return redirect('/topologie/index_stack') return redirect('/topologie/index_stack')
return form({'objet': stack}, 'topologie/delete.html', request) return form({'objet': stack}, 'topologie/delete.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def edit_switchs_stack(request, stack_id): def edit_switchs_stack(request, stack_id):
"""Permet d'éditer la liste des switches dans une stack et l'ajouter"""
try: try:
stack = Stack.objects.get(pk=stack_id) stack = Stack.objects.get(pk=stack_id)
except Stack.DoesNotExist: except Stack.DoesNotExist:
@ -264,30 +330,36 @@ def edit_switchs_stack(request,stack_id):
context = {'stack': stack} context = {'stack': stack}
context['switchs_stack'] = stack.switchs_set.all() context['switchs_stack'] = stack.switchs_set.all()
context['switchs_autres'] = Switch.object.filter(stack=None) context['switchs_autres'] = Switch.object.filter(stack=None)
pass
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def new_switch(request): def new_switch(request):
""" Creation d'un switch. Cree en meme temps l'interface et la machine associée. """ Creation d'un switch. Cree en meme temps l'interface et la machine
Vue complexe. Appelle successivement les 4 models forms adaptés : machine, associée. Vue complexe. Appelle successivement les 4 models forms
interface, domain et switch""" adaptés : machine, interface, domain et switch"""
switch = NewSwitchForm(request.POST or None) switch = NewSwitchForm(request.POST or None)
machine = NewMachineForm(request.POST or None) machine = NewMachineForm(request.POST or None)
interface = AddInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',))) interface = AddInterfaceForm(
domain = AliasForm(request.POST or None, infra=request.user.has_perms(('infra',))) request.POST or None,
infra=request.user.has_perms(('infra',))
)
domain = AliasForm(
request.POST or None,
infra=request.user.has_perms(('infra',))
)
if switch.is_valid() and machine.is_valid() and interface.is_valid(): if switch.is_valid() and machine.is_valid() and interface.is_valid():
options, created = AssoOption.objects.get_or_create() options, _created = AssoOption.objects.get_or_create()
user = options.utilisateur_asso user = options.utilisateur_asso
if not user: if not user:
messages.error(request, "L'user association n'existe pas encore, veuillez le créer ou le linker dans preferences") messages.error(request, "L'user association n'existe pas encore,\
veuillez le créer ou le linker dans preferences")
return redirect("/topologie/") return redirect("/topologie/")
new_machine = machine.save(commit=False) new_machine = machine.save(commit=False)
new_machine.user = user new_machine.user = user
new_interface = interface.save(commit=False) new_interface = interface.save(commit=False)
new_switch = switch.save(commit=False) new_switch_instance = switch.save(commit=False)
new_domain = domain.save(commit=False) new_domain_instance = domain.save(commit=False)
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
new_machine.save() new_machine.save()
reversion.set_user(request.user) reversion.set_user(request.user)
@ -297,58 +369,91 @@ def new_switch(request):
new_interface.save() new_interface.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Création") reversion.set_comment("Création")
new_domain.interface_parent = new_interface new_domain_instance.interface_parent = new_interface
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
new_domain.save() new_domain_instance.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Création") reversion.set_comment("Création")
new_switch.switch_interface = new_interface new_switch_instance.switch_interface = new_interface
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
new_switch.save() new_switch_instance.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Création") reversion.set_comment("Création")
messages.success(request, "Le switch a été crée") messages.success(request, "Le switch a été crée")
return redirect("/topologie/") return redirect("/topologie/")
return form({'topoform':switch, 'machineform': machine, 'interfaceform': interface, 'domainform': domain}, 'topologie/switch.html', request) return form({
'topoform': switch,
'machineform': machine,
'interfaceform': interface,
'domainform': domain
}, 'topologie/switch.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def edit_switch(request, switch_id): def edit_switch(request, switch_id):
""" Edition d'un switch. Permet de chambre nombre de ports, place dans le stack, """ Edition d'un switch. Permet de chambre nombre de ports,
interface et machine associée""" place dans le stack, interface et machine associée"""
try: try:
switch = Switch.objects.get(pk=switch_id) switch = Switch.objects.get(pk=switch_id)
except Switch.DoesNotExist: except Switch.DoesNotExist:
messages.error(request, u"Switch inexistant") messages.error(request, u"Switch inexistant")
return redirect("/topologie/") return redirect("/topologie/")
switch_form = EditSwitchForm(request.POST or None, instance=switch) switch_form = EditSwitchForm(request.POST or None, instance=switch)
machine_form = EditMachineForm(request.POST or None, instance=switch.switch_interface.machine) machine_form = EditMachineForm(
interface_form = EditInterfaceForm(request.POST or None, instance=switch.switch_interface) request.POST or None,
domain_form = AliasForm(request.POST or None, infra=request.user.has_perms(('infra',)), instance=switch.switch_interface.domain) instance=switch.switch_interface.machine
if switch_form.is_valid() and machine_form.is_valid() and interface_form.is_valid(): )
interface_form = EditInterfaceForm(
request.POST or None,
instance=switch.switch_interface
)
domain_form = AliasForm(
request.POST or None,
infra=request.user.has_perms(('infra',)),
instance=switch.switch_interface.domain
)
if switch_form.is_valid() and machine_form.is_valid()\
and interface_form.is_valid():
new_interface = interface_form.save(commit=False) new_interface = interface_form.save(commit=False)
new_machine = machine_form.save(commit=False) new_machine = machine_form.save(commit=False)
new_switch = switch_form.save(commit=False) new_switch_instance = switch_form.save(commit=False)
new_domain = domain_form.save(commit=False) new_domain = domain_form.save(commit=False)
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
new_machine.save() new_machine.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in machine_form.changed_data)) reversion.set_comment(
"Champs modifié(s) : %s" % ', '.join(
field for field in machine_form.changed_data
)
)
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
new_interface.save() new_interface.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in interface_form.changed_data)) reversion.set_comment("Champs modifié(s) : %s" % ', '.join(
field for field in interface_form.changed_data)
)
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
new_domain.save() new_domain.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in domain_form.changed_data)) reversion.set_comment("Champs modifié(s) : %s" % ', '.join(
field for field in domain_form.changed_data)
)
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
new_switch.save() new_switch_instance.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in switch_form.changed_data)) reversion.set_comment("Champs modifié(s) : %s" % ', '.join(
field for field in switch_form.changed_data)
)
messages.success(request, "Le switch a bien été modifié") messages.success(request, "Le switch a bien été modifié")
return redirect("/topologie/") return redirect("/topologie/")
return form({'topoform':switch_form, 'machineform': machine_form, 'interfaceform': interface_form, 'domainform': domain_form}, 'topologie/switch.html', request) return form({
'topoform': switch_form,
'machineform': machine_form,
'interfaceform': interface_form,
'domainform': domain_form
}, 'topologie/switch.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
@ -364,6 +469,7 @@ def new_room(request):
return redirect("/topologie/index_room/") return redirect("/topologie/index_room/")
return form({'topoform': room}, 'topologie/topo.html', request) return form({'topoform': room}, 'topologie/topo.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def edit_room(request, room_id): def edit_room(request, room_id):
@ -378,11 +484,14 @@ def edit_room(request, room_id):
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
room.save() room.save()
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in room.changed_data)) reversion.set_comment("Champs modifié(s) : %s" % ', '.join(
field for field in room.changed_data)
)
messages.success(request, "La chambre a bien été modifiée") messages.success(request, "La chambre a bien été modifiée")
return redirect("/topologie/index_room/") return redirect("/topologie/index_room/")
return form({'topoform': room}, 'topologie/topo.html', request) return form({'topoform': room}, 'topologie/topo.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def del_room(request, room_id): def del_room(request, room_id):
@ -400,6 +509,10 @@ def del_room(request, room_id):
reversion.set_comment("Destruction") reversion.set_comment("Destruction")
messages.success(request, "La chambre/prise a été détruite") messages.success(request, "La chambre/prise a été détruite")
except ProtectedError: except ProtectedError:
messages.error(request, "La chambre %s est affectée à un autre objet, impossible de la supprimer (switch ou user)" % room) messages.error(request, "La chambre %s est affectée à un autre objet,\
impossible de la supprimer (switch ou user)" % room)
return redirect("/topologie/index_room/") return redirect("/topologie/index_room/")
return form({'objet': room, 'objet_name': 'Chambre'}, 'topologie/delete.html', request) return form({
'objet': room,
'objet_name': 'Chambre'
}, 'topologie/delete.html', request)