3

I have a django form that allows a user to select multiple options:

CARDS = (
    ("visa", "Visa"),
    ("mastercard", "MasterCard"),
)

class PaymentForm(forms.ModelForm):
    credit_cards = forms.MultipleChoiceField(choices=CARDS, widget=forms.CheckboxSelectMultiple)
    # ... etc.

I have the form's associated model setup as:

class Payment(models.Model):
    user = models.OneToOneField(User)
    credit_cards = models.CharField(choices=CARDS, max_length=100)
    # ... etc.

But I'm thinking that a CharField with the choices parameter can only accept a single choice because my form never validates and I get an error like:

Value u"[u'visa']" is not a valid choice.

And it sure looks like a valid choice.

I've seen that some people get this working with a ManyToManyField on the model side (which I'd expect) but building a model just for a static list of credit card types seems overkill.

So: is there a specific model field type or different form configuration I should be using to support multiple selections from a pre-defined list of options?

Thanks.

Community
  • 1
  • 1
codebyren
  • 690
  • 6
  • 10

1 Answers1

2

http://djangosnippets.org/snippets/1200/

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
  • 1
    Thanks, I did see this snippet (probably should have mentioned that) but I figured that 2+ years later, the functionality would be built into django. Guess not. – codebyren Feb 07 '11 at 02:14
  • You may want to look at https://github.com/goinnn/django-multiselectfield which is inspired by that snippet – mohd4482 Dec 07 '17 at 22:07