Merge pull request #3885 from hSaria/568-csv-import-cf

Fixes #568: CSV import/export of custom fields
This commit is contained in:
Jeremy Stretch
2020-01-29 10:11:40 -05:00
committed by GitHub
11 changed files with 114 additions and 25 deletions

View File

@@ -442,6 +442,23 @@ class CSVChoiceField(forms.ChoiceField):
return self.choice_values[value]
class CustomFieldChoiceField(forms.TypedChoiceField):
"""
Accept human-friendly label as input, and return the database value. If the label is not matched, the normal,
value-based input is assumed.
"""
def __init__(self, choices, *args, **kwargs):
super().__init__(choices=choices, *args, **kwargs)
self.choice_values = {label: value for value, label in unpack_grouped_choices(choices)}
def clean(self, value):
# Check if the value is actually a label
if value in self.choice_values:
return self.choice_values[value]
return super().clean(value)
class ExpandableNameField(forms.CharField):
"""
A field which allows for numeric range expansion

View File

@@ -88,15 +88,27 @@ class ObjectListView(View):
Export the queryset of objects as comma-separated value (CSV), using the model's to_csv() method.
"""
csv_data = []
custom_fields = []
# Start with the column headers
headers = ','.join(self.queryset.model.csv_headers)
csv_data.append(headers)
headers = self.queryset.model.csv_headers.copy()
# Add custom field headers, if any
if hasattr(self.queryset.model, 'get_custom_fields'):
for custom_field in self.queryset.model().get_custom_fields():
headers.append(custom_field.name)
custom_fields.append(custom_field.name)
csv_data.append(','.join(headers))
# Iterate through the queryset appending each object
for obj in self.queryset:
data = csv_format(obj.to_csv())
csv_data.append(data)
data = obj.to_csv()
for custom_field in custom_fields:
data += (obj.cf.get(custom_field, ''),)
csv_data.append(csv_format(data))
return '\n'.join(csv_data)