Opened 5 years ago

Closed 5 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


class MyModelAdmin(admin.ModelAdmin):
	def formfield_for_dbfield(self, db_field, **kwargs):
		if == '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 Changed 5 years ago by Tim Graham

This may be addressed in master (1.7) with #20649 - could you take a look and see if that meets your use case?

comment:2 Changed 5 years ago by Claude Paroz

Resolution: worksforme
Status: newclosed

That change:
...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.

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