def create_column_controls(self, column_headers): """ Adds fields to the form for extra columns found in the spreadsheet. Returns a list of dictionaries containing the column label and the names of the fields """ column_controls = [] for header in column_headers: header_key = slugify_with(header) include_field = forms.BooleanField(label=' ', required=False) include_field_name = 'column_%s_include' % header_key label_field = forms.CharField(label=' ', initial=header.title()) label_field_name = 'column_%s_label' % header_key type_field = forms.ChoiceField(label=' ', choices=VALUE_TYPE_CHOICES, required=True) type_field_name = 'column_%s_type' % header_key fields = [] fields.append((include_field_name, include_field)) fields.append((label_field_name, label_field)) fields.append((type_field_name, type_field)) self.form.fields = OrderedDict(self.form.fields.items() + fields) column_controls.append(dict(header=header, include_field=include_field_name, label_field=label_field_name, type_field=type_field_name)) return column_controls
def pre_save(self, task): extra_fields = [] cleaned_data = self.form.cleaned_data # enumerate the columns which the user has chosen to include as fields for column in self.column_controls: if cleaned_data[column['include_field']]: label = cleaned_data[column['label_field']] label = label.strip() value_type = cleaned_data[column['type_field']] org = self.derive_org() field_key = slugify_with(label) existing_field = ContactField.get_by_label(org, label) if existing_field: field_key = existing_field.key extra_fields.append(dict(key=field_key, header=column['header'], label=label, type=value_type)) # update the extra_fields in the task's params params = json.loads(task.import_params) params['extra_fields'] = extra_fields task.import_params = json.dumps(params) return task
def clean(self): # don't allow users to specify field keys or labels re_col_name_field = re.compile(r'column_\w+_label') for key, value in self.data.items(): if re_col_name_field.match(key): field_label = value field_key = slugify_with(value) if not ContactField.is_valid_label(field_label): raise ValidationError(_("Field names can only contain letters, numbers, spaces and hypens")) if field_key in RESERVED_CONTACT_FIELDS: raise ValidationError(_("%s is a reserved name for contact fields") % value) return self.cleaned_data
def pre_save(self, task): extra_fields = [] cleaned_data = self.form.cleaned_data # enumerate the columns which the user has chosen to include as fields for column in self.column_controls: if cleaned_data[column['include_field']]: label = cleaned_data[column['label_field']] value_type = cleaned_data[column['type_field']] field_key = slugify_with(label) extra_fields.append(dict(key=field_key, header=column['header'], label=label, type=value_type)) # update the extra_fields in the task's params params = json.loads(task.import_params) params['extra_fields'] = extra_fields task.import_params = json.dumps(params) return task