From 9e500391f2186fdaa3453384ee4ad4bbddc36cdc Mon Sep 17 00:00:00 2001
From: Benjamin Bertrand <benjamin.bertrand@esss.se>
Date: Wed, 24 Apr 2019 21:29:00 +0200
Subject: [PATCH] Fix exception when no network selected

1. It's possible to erase the network when creating a host.
The exception raised was due to the ip_in_range validator
where a select using the network_id is performed.
This is now catched to raise a ValidationError.
2. Add some javascript to remove the is-invalid class on the network and
IP fields when changing them

JIRA INFRA-810 #action In Progress
---
 app/network/forms.py   |  4 ++++
 app/static/js/hosts.js | 10 ++++++++++
 2 files changed, 14 insertions(+)

diff --git a/app/network/forms.py b/app/network/forms.py
index 256875a..ad7b7a1 100644
--- a/app/network/forms.py
+++ b/app/network/forms.py
@@ -56,6 +56,10 @@ def starts_with_hostname(form, field):
 def ip_in_network(form, field):
     """Check that the IP is in the network"""
     network_id_field = form["network_id"]
+    if not network_id_field.data:
+        raise validators.ValidationError(
+            "Can't validate the IP. No network was selected."
+        )
     network = models.Network.query.get(network_id_field.data)
     ip = ipaddress.ip_address(field.data)
     if ip not in network.network_ip:
diff --git a/app/static/js/hosts.js b/app/static/js/hosts.js
index 75ac215..78bac16 100644
--- a/app/static/js/hosts.js
+++ b/app/static/js/hosts.js
@@ -36,6 +36,7 @@ $(document).ready(function() {
     // and update the IP field
     var network_id = $("#network_id").val();
     if ( network_id !== "" ) {
+      $("#ip").removeClass("is-invalid");
       $.getJSON(
         $SCRIPT_ROOT + "/network/_retrieve_first_available_ip/" + network_id,
         function(json) {
@@ -83,6 +84,13 @@ $(document).ready(function() {
     set_default_ip();
   }
 
+  // On page load if the network_id is invalid, it's because an empty entry was submitted
+  // remove the default value to make it clear
+  if( ($("#hostForm").length || $("#interfaceForm").length) && $("#network_id").hasClass("is-invalid") ) {
+    var network_id_selectize = $("#network_id")[0].selectize;
+    network_id_selectize.clear(true);
+  }
+
   // Clear the default value so that the user can start typing directly
   // or click a dropdown item
   $("#network_id").next(".selectize-control").on( 'click', function () {
@@ -92,6 +100,8 @@ $(document).ready(function() {
 
   // Set the default IP when changing network
   $("#network_id").on('change', function() {
+    $(this).removeClass("is-invalid");
+    $(this).next(".selectize-control").removeClass("is-invalid");
     set_default_ip();
   });
 
-- 
GitLab