Strip ArrayField input from admin

20 views
Skip to first unread message

Erik Cederstrand

unread,
Aug 18, 2015, 4:54:58 AM8/18/15
to Django Users
Hi list

I have a model with a field defined like this:

categories = ArrayField(models.CharField(max_length=32))


This field is accessible via the admin interface, and when I enter comma-separated values in the charfield, they are stored as an array in the DB.

However, I just discovered that if I enter comma+space separated values, e.g. "teachers, locations, students", it gets converted to ['teachers', ' locations', ' students'] which is not what I want. How go I get the ArrayField to strip the values after splitting by comma?

Thanks,
Erik

Erik Cederstrand

unread,
Sep 3, 2015, 2:46:06 AM9/3/15
to Django Users
Well, that was easy. Just subclass ArrayField:

class StrippedArrayField(ArrayField):
def pre_save(self, model_instance, add):
stripped_array = [s.strip() for s in getattr(model_instance, self.attname)]
setattr(model_instance, self.attname, stripped_array)
return stripped_array


Erik
Reply all
Reply to author
Forward
0 new messages