Opened 11 years ago
Closed 11 years ago
#21224 closed Uncategorized (worksforme)
TypedChoiceField does not properly coerce 'None' in certain circumstances
Reported by: | anonymous | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.5 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
class MyModelAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'integerfield': return forms.TypedChoiceField(choices=((None,'Undecided'),(-1, 'Reject'), (0, 'Neutral'), (1,'Accept')))
Selecting 'Undecided' here results in the error message "'None' must be an integer"
In order to fix this I have to add the following param to TypedChoiceField:
coerce=lambda v: int(v) if v and v != 'None' else None
If I try this instead it results in the error "Select a valid choice. None is not one of the available choices.":
coerce=lambda v: int(v) if v else None
It appears that the None choice is getting coerced to a string before it passes into TypedChoiceField.to_python (or wherever it gets passed to first)?
Change History (2)
comment:1 by , 11 years ago
comment:2 by , 11 years ago
Resolution: | → worksforme |
---|---|
Status: | new → closed |
That change: https://github.com/django/django/commit/1123f4551158b7fc65d3bd88c375a4517dcd0720#diff-aee6730bae795d31efec3c5d014804a9R511
...should solve your issue, as the None
choice will be rendered as the empty string in the option value, then coercion should consider it as the empty value. Reopen if you can reproduce an issue with master code.
This may be addressed in master (1.7) with #20649 - could you take a look and see if that meets your use case?