Repository: netbox-community/netbox

Issue:
Exception when creating a new interface via API with VLANs assigned
### Issue type
[ ] Feature request <!-- An enhancement of existing functionality -->
[x] Bug report      <!-- Unexpected or erroneous behavior -->
[ ] Documentation   <!-- A modification to the documentation -->

### Environment
* Python version:  3.5.2
* NetBox version:  2.3.0

### Description
Attempting to create a new interface via the API with one or more assigned tagged or untagged VLANs raises a ValueError:

```
ValueError: "<Interface: eth0>" needs to have a value for field "id" before this many-to-many relationship can be used.
```

For example:

```
curl -X POST \
-H "Authorization: Token <TOKEN>" \
-H "Content-Type: application/json" \
-H "Accept: application/json; indent=4" \
http://localhost:8000/api/dcim/interfaces/ \
--data '{
  "enabled": true,
  "device": 123,
  "name": "eth0",
  "mgmt_only": true,
  "untagged_vlan": null,
  "mac_address": null,
  "form_factor": "1000",
  "mode": null,
  "description": "testing",
  "tagged_vlans": [456],
  "lag": null
}'
```

This also occurs when an empty list of VLAN PKs is provided. It does not occur when the `tagged_vlans` and `untagged_vlans` fields are not present.



Discussion:
Whoops. Stupid M2M relations... Looking back at the testing I did, it was only on existing interfaces. Should be easy enough to fix in the view. Would you like me to take care of this @jeremystretch ?
@lampwins Go for it

Resolving patch:
diff --git a/netbox/dcim/api/serializers.py b/netbox/dcim/api/serializers.py
--- a/netbox/dcim/api/serializers.py
+++ b/netbox/dcim/api/serializers.py
@@ -743,7 +743,7 @@ def validate(self, data):
             if vlan.site not in [device.site, None]:
                 raise serializers.ValidationError({
                     'tagged_vlans': "VLAN {} must belong to the same site as the interface's parent device, or it must "
-                                   "be global.".format(vlan)
+                                    "be global.".format(vlan)
                 })
 
         return super(WritableInterfaceSerializer, self).validate(data)


Test patch:
diff --git a/netbox/dcim/tests/test_api.py b/netbox/dcim/tests/test_api.py
--- a/netbox/dcim/tests/test_api.py
+++ b/netbox/dcim/tests/test_api.py
@@ -12,6 +12,7 @@
     InventoryItem, Platform, PowerPort, PowerPortTemplate, PowerOutlet, PowerOutletTemplate, Rack, RackGroup,
     RackReservation, RackRole, Region, Site, VirtualChassis,
 )
+from ipam.models import VLAN
 from extras.models import Graph, GRAPH_TYPE_INTERFACE, GRAPH_TYPE_SITE
 from users.models import Token
 from utilities.tests import HttpStatusMixin
@@ -2258,6 +2259,10 @@ def setUp(self):
         self.interface2 = Interface.objects.create(device=self.device, name='Test Interface 2')
         self.interface3 = Interface.objects.create(device=self.device, name='Test Interface 3')
 
+        self.vlan1 = VLAN.objects.create(name="Test VLAN 1", vid=1)
+        self.vlan2 = VLAN.objects.create(name="Test VLAN 2", vid=2)
+        self.vlan3 = VLAN.objects.create(name="Test VLAN 3", vid=3)
+
     def test_get_interface(self):
 
         url = reverse('dcim-api:interface-detail', kwargs={'pk': self.interface1.pk})
@@ -2309,6 +2314,26 @@ def test_create_interface(self):
         self.assertEqual(interface4.device_id, data['device'])
         self.assertEqual(interface4.name, data['name'])
 
+    def test_create_interface_with_802_1q(self):
+
+        data = {
+            'device': self.device.pk,
+            'name': 'Test Interface 4',
+            'tagged_vlans': [self.vlan1.id, self.vlan2.id],
+            'untagged_vlan': self.vlan3.id
+        }
+
+        url = reverse('dcim-api:interface-list')
+        response = self.client.post(url, data, format='json', **self.header)
+
+        self.assertHttpStatus(response, status.HTTP_201_CREATED)
+        self.assertEqual(Interface.objects.count(), 4)
+        interface5 = Interface.objects.get(pk=response.data['id'])
+        self.assertEqual(interface5.device_id, data['device'])
+        self.assertEqual(interface5.name, data['name'])
+        self.assertEqual(interface5.tagged_vlans.count(), 2)
+        self.assertEqual(interface5.untagged_vlan.id, data['untagged_vlan'])
+
     def test_create_interface_bulk(self):
 
         data = [
@@ -2335,6 +2360,44 @@ def test_create_interface_bulk(self):
         self.assertEqual(response.data[1]['name'], data[1]['name'])
         self.assertEqual(response.data[2]['name'], data[2]['name'])
 
+    def test_create_interface_802_1q_bulk(self):
+
+        data = [
+            {
+                'device': self.device.pk,
+                'name': 'Test Interface 4',
+                'tagged_vlans': [self.vlan1.id],
+                'untagged_vlan': self.vlan2.id,
+            },
+            {
+                'device': self.device.pk,
+                'name': 'Test Interface 5',
+                'tagged_vlans': [self.vlan1.id],
+                'untagged_vlan': self.vlan2.id,
+            },
+            {
+                'device': self.device.pk,
+                'name': 'Test Interface 6',
+                'tagged_vlans': [self.vlan1.id],
+                'untagged_vlan': self.vlan2.id,
+            },
+        ]
+
+        url = reverse('dcim-api:interface-list')
+        response = self.client.post(url, data, format='json', **self.header)
+
+        self.assertHttpStatus(response, status.HTTP_201_CREATED)
+        self.assertEqual(Interface.objects.count(), 6)
+        self.assertEqual(response.data[0]['name'], data[0]['name'])
+        self.assertEqual(response.data[1]['name'], data[1]['name'])
+        self.assertEqual(response.data[2]['name'], data[2]['name'])
+        self.assertEqual(len(response.data[0]['tagged_vlans']), 1)
+        self.assertEqual(len(response.data[1]['tagged_vlans']), 1)
+        self.assertEqual(len(response.data[2]['tagged_vlans']), 1)
+        self.assertEqual(response.data[0]['untagged_vlan'], self.vlan2.id)
+        self.assertEqual(response.data[1]['untagged_vlan'], self.vlan2.id)
+        self.assertEqual(response.data[2]['untagged_vlan'], self.vlan2.id)
+
     def test_update_interface(self):
 
         lag_interface = Interface.objects.create(