Opened 7 years ago

Closed 7 years ago

#27495 closed Bug (needsinfo)

MultipleChoiceField isn't working with options longer than 1 character

Reported by: Mario Härtwig Owned by: nobody
Component: Forms Version: 1.10
Severity: Normal Keywords: MultipleChoiceField
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


The MultipleChoiceField doesn't seem to work it the name of the option in the choices list is longer than one character. If the options specified in the choices list are longer, the selected values cannot be restored after the form has been saved.

(('1', 'foo'),
  ('b', 'bar'),)

works whereas

(('foo', 'foo'),
  ('bar, 'bar'),)

The values are saved as a string inside the database (e.g. "['foo', 'bar']"). The problem seems to be line Line 564 in forms/ This line tries to convert the array-like string from the database to an array without deserializing it before.

The string "['foo', 'bar']", for instance, is converted to {'o', ' ', 'a', "'", 'b', 'r', ']', ',', 'f', '['}.

I've created a fix that solves the issue and I could create a pull request. However, I'm wondering if there shouldn't be some kind of deserialization of the array-like string before. And why isn't the array stored in a JSON strucure within the database (with double quotes). Am I missing something?

Attachments (1)

27495-test.diff (970 bytes) - added by Tim Graham 7 years ago.

Download all attachments as: .zip

Change History (4)

comment:1 Changed 7 years ago by Tim Graham

Could you please include a more complete example to reproduce the issue? I wrote the attached and everything seems to be working as expected but I guess it doesn't demonstrate what you're doing.

Changed 7 years ago by Tim Graham

Attachment: 27495-test.diff added

comment:2 Changed 7 years ago by Mario Härtwig

Thanks for your reply. Your test works for me as well. However, when using a widget with your choices-list for a model field, saving the model and re-opening the form, no option is selected. The line mentioned above turns

['1A', '2B']


{' ', 'A', ']', ',', '[', "'", '1', '2', 'B'}

Your test doesn't save anything to the database which is why everything seem to work. You should be able to reproduce it when using your choices-list in an app. If not, I have to dive deeper into the Django test suite for being able to write a test demonstrating the issue.

comment:3 Changed 7 years ago by Tim Graham

Component: UncategorizedForms
Resolution: needsinfo
Status: newclosed
Type: UncategorizedBug

I guess maybe you're using MultipleChoiceField with CharField? If so, then no, I wouldn't expect MultipleChoiceField to be an appropriate form field. If you want to provide more details and/or a patch that doesn't break things, feel free to reopen. Thanks.

Note: See TracTickets for help on using tickets.
Back to Top