Skip to content

Commit

Permalink
Fixes netbox-community#422: Added ability to encapsulate within doubl…
Browse files Browse the repository at this point in the history
…e quotes values which contain commas
  • Loading branch information
jeremystretch committed Aug 3, 2016
1 parent b949daf commit 62dead2
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions netbox/utilities/forms.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import csv
import re

from django import forms
Expand Down Expand Up @@ -118,7 +119,8 @@ def __init__(self, query_key, query_url, field_to_update, obj_label=None, *args,

class CSVDataField(forms.CharField):
"""
A field for comma-separated values (CSV)
A field for comma-separated values (CSV). Values containing commas should be encased within double quotes. Example:
'"New York, NY",new-york-ny,Other stuff' => ['New York, NY', 'new-york-ny', 'Other stuff']
"""
csv_form = None

Expand All @@ -136,16 +138,16 @@ def __init__(self, csv_form, *args, **kwargs):
def to_python(self, value):
# Return a list of dictionaries, each representing an individual record
records = []
for i, row in enumerate(value.split('\n'), start=1):
if row.strip():
values = row.strip().split(',')
if len(values) < len(self.columns):
reader = csv.reader(value.splitlines())
for i, row in enumerate(reader, start=1):
if row:
if len(row) < len(self.columns):
raise forms.ValidationError("Line {}: Field(s) missing (found {}; expected {})"
.format(i, len(values), len(self.columns)))
elif len(values) > len(self.columns):
.format(i, len(row), len(self.columns)))
elif len(row) > len(self.columns):
raise forms.ValidationError("Line {}: Too many fields (found {}; expected {})"
.format(i, len(values), len(self.columns)))
record = dict(zip(self.columns, values))
.format(i, len(row), len(self.columns)))
record = dict(zip(self.columns, row))
records.append(record)
return records

Expand Down

0 comments on commit 62dead2

Please sign in to comment.