Last active
September 2, 2016 10:45
-
-
Save webjunkie/8280e6af65229c409720296a9292b2f4 to your computer and use it in GitHub Desktop.
MultipleChoiceCommaField for Django reads and saves comma separated values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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