Skip to content

Instantly share code, notes, and snippets.

@webjunkie
Last active September 2, 2016 10:45
Show Gist options
  • Save webjunkie/8280e6af65229c409720296a9292b2f4 to your computer and use it in GitHub Desktop.
Save webjunkie/8280e6af65229c409720296a9292b2f4 to your computer and use it in GitHub Desktop.
MultipleChoiceCommaField for Django reads and saves comma separated values
from django import forms
from django.core.exceptions import ValidationError
class MultipleChoiceCommaField(forms.MultipleChoiceField):
"""
Store a comma separated list of multiple choice values in a CharField/TextField
"""
widget = forms.CheckboxSelectMultiple
def prepare_value(self, value):
if value and not isinstance(value, (list, tuple)):
return value.split(",")
return value
def to_python(self, value):
if not value:
return ""
elif not isinstance(value, (list, tuple)):
raise ValidationError(self.error_messages['invalid_list'],
code='invalid_list')
return ",".join(smart_text(val) for val in value)
def validate(self, value):
value = value.split(",") if value else []
return super(MultipleChoiceCommaField, self).validate(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment