Monday, December 21, 2020

MultipleChoiceField form bug?

Hi all,

I've ran into some unexpected behavior while testing a ModelForm with a MultipleChoiceField and am trying to determine if this is a bug, or if maybe I'm doing something out of the ordinary.

In the form, I'm generating the MultipleChoiceField choices on the fly. e.g. `OPTIONS = ((m.id, m.name) for m in Model.objects.all())` then assigning `OPTIONS` to the `choices` attribute in the field declaration.

When running the test the form generates the choices from the non-test db, which results in a failure, as I'm creating the model instance for POST in the test. So because of this behavior, the instance created in the test isn't part of the form choices.

It seems like:
- ./manage.py test
- Generate form choices
- Instantiate Test
- Test creates expected choice(s) and calls view with POST data
- form.is_valid() fails due to generated test instance not being in choices

It seems odd to me that the form is (or at least parts of it are) being built before any direct reference to it is instantiated. But this may be normal/expected behavior. I've seen the same behavior in 1.11 and 3.1.4, so it's most likely that my method for dynamically generating choices isn't kosher.

Anyway, if this sounds like a possible bug let me know and I'll submit an issue with steps to reproduce, or provide more information here on request. 


Thanks,
Benny

No comments:

Post a Comment