Opened 2 years ago

Closed 2 years ago

#22808 closed Bug (fixed)

ModelMultipleChoiceField does not properly check if value is valid

Reported by: mattias.lindvall@… Owned by: nip3o
Component: Forms Version: 1.6
Severity: Normal Keywords: modelform, afraid-to-commit
Cc: maxime.turcotte@… Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no


ModelMultipleChoiceField does try to check if value is valid by doing a query here:

However, it only cathes ValueError, assuming that filter() is capable of even using the value.
If the value is a weird data type like list or dict, the call to filter throws TypeError.
ModelMultipleChoiceField.clean should catch TypeError, in addition to ValueError, on line 1187.

Here is gist with a complete minimal app that demonstrates how this can happen:
Specifically the file: 4.

It is tested with 1.6.5, using 100% default settings in a clean test project.

Change History (9)

comment:1 Changed 2 years ago by maxocub

  • Cc maxime.turcotte@… added
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 2 years ago by maxocub

  • Easy pickings set
  • Version changed from 1.5 to 1.6

comment:3 Changed 2 years ago by EvilDMP

  • Keywords afraid-to-commit added

comment:4 Changed 2 years ago by bmispelon

  • Triage Stage changed from Unreviewed to Accepted


Looking at django/forms/, it seems that there is precedent for catching (ValueError, TypeError) so I think it makes sense.

The same error seems to be present in ModelChoiceField so both should be fixed as part of this ticket.


comment:5 Changed 2 years ago by anonymous

comment:6 Changed 2 years ago by timo

  • Needs tests set

It needs a test (or tests). Please uncheck "Needs tests" if you can update it, thanks.

comment:7 Changed 2 years ago by nip3o

  • Owner changed from nobody to nip3o
  • Status changed from new to assigned

Working on this during EP14 sprints.

Last edited 2 years ago by nip3o (previous) (diff)

comment:8 Changed 2 years ago by nip3o

  • Has patch set
  • Needs tests unset

New PR with the existing patch applied and including test cases.

comment:9 Changed 2 years ago by Tim Graham <timograham@…>

  • Resolution set to fixed
  • Status changed from assigned to closed

In cdc25ac4747bf5a6cdc2e70461c2d43c54529d35:

Fixed #22808 -- Made ModelMultipleChoiceField validation more robust to invalid data types..

Thanks Mattias Lindvall for the report and inital patch.

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