#30395: ModelForm: allow to declaratively specify field classes corresponding to
model fields with choices
---------------------------------------+---------------------------
Reporter: Quentin | Owner: nobody
Type: New feature | Status: new
Component: Forms | Version: 2.2
Severity: Normal | Keywords: ModelForm
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
---------------------------------------+---------------------------
If a model field has choices, `Model.formfield` will disregard the
`form_class` keyword argument (plucked from
`ModelForm.Meta.field_classes`), in favor of `choices_form_class`, which
is not set by the ModelForm field generation machinery, and defaults to
`TypedChoiceField`. As a result, the following won't work:
{{{#!python
class Language(models.Model):
LANGUAGES = (
('FR', 'French'),
('EN', 'English')
)
iso = models.CharField(max_length=3, choices=LANGUAGES)
class SloppyIsoField(CharField):
"""Choice field that strips and uppercases language codes"""
def to_python(self, value):
value = super().to_python(value)
return value.strip().upper()
class LanguageForm(forms.ModelForm):
class Meta:
fields = ('iso',)
field_classes = {
'iso': SloppyIsoField
}
}}}
Granted, this is a bit contrived, but it might be worth mentioning the
caveat in the docs. Or maybe allow a `Meta.choices_field_classes`? If this
is relevant I'd happily contribute.
--
Ticket URL: <https://code.djangoproject.com/ticket/30395>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/049.a078fbea284d1f4741421dd5fae1ff4d%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.