0

I am trying to use a MultipleChoiceField with a ModelForm but am obviously implementing it wrong.

There are two linked? issues:

  • The question only submits of the user selects nothing
  • The question displays the default option "------" which i want to remove
    • If I remove the "-----" by removing blank=True the question will not submit at all, see image below.

enter image description here

If anyone can tell me what I am going wrong it would be greatly appriciated.

modles.py

ELECTIONS = (
    ('NONE', 'None'),
    ('LOCAL', 'Local elections'),
    ('STATE', 'State elections e.g. Governorship'),
    ('NATIONAL', 'National elections e.g. Congress and Senate'),
    ('PRESIDENTIAL', 'Presidential elections'),
    ('OTHER', 'Other'),
    ('DONT_KNOW', "Don't know"),
    )

elections = models.CharField(null=True, max_length=100, blank=True, default=None, choices = ELECTIONS, verbose_name = 'Which elections do you regularly vote in or intend to vote in? Select all that apply.')

forms.py

class SurveyFormD(forms.ModelForm): # Political Viewpoints

    class Meta:
        model = Person
        fields = ['liberal_conservative', 'democrat_republican', 'voting_rights', 'elections']        

        widgets = {'liberal_conservative' : forms.RadioSelect,
                   'democrat_republican' : forms.RadioSelect,
                   'voting_rights' : forms.RadioSelect,
                   'elections' : forms.CheckboxSelectMultiple,}
Deepend
  • 4,057
  • 17
  • 60
  • 101

1 Answers1

1

The problem is that you're using a MultipleChoiceField in your form, but you have a CharField in your model. A CharField stores strings, not lists, so your model is expecting a single (string) value from the list of choices, not the list [u'LOCAL', u'NATIONAL', u'PRESIDENTIAL'] that your CheckboxSelectMultiple is returning.

You could make elections a ManyToMany field and thus store multiple values in the single field elections.

Or check out this question for further clarification.

Community
  • 1
  • 1
Dan Russell
  • 960
  • 8
  • 22