Opened 9 months ago

Closed 8 months 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)?

Attachments (0)

Change History (2)

comment:1 Changed 9 months ago by timo

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

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 8 months ago by claudep

  • Resolution set to worksforme
  • Status changed from new to closed

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.

Add Comment

Modify Ticket

Change Properties
<Author field>
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.