#19617 closed New feature (fixed)
mixins on ModelForms
| Reported by: | Daniele Procida | Owned by: | loic84 |
|---|---|---|---|
| Component: | Forms | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Accepted | |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
At present, this sort of thing is not possible:
# define a reusable mixin for ModelForms
InputURLMixin(object):
input_url = forms.CharField(max_length=255, required = False,
help_text=u"<strong>External URL</strong> not found above? Enter a new one.",
)
# the form
class LinkItemForm(InputURLMixin, forms.ModelForm):
[...]
# the admin class
class PluginInlineLink(admin.StackedInline):
form = LinkItemForm
[...]
fieldsets = # if fieldsets contains "input_url": "Unknown field(s) (input_url) specified"
In other words, it's not possible for a ModelForm to inherit from a Mixin(object) or indeed Mixin(Form).
In the former case, the Mixin(object) fails the test in forms.ModelFormMetaclass.__new__() that would allow it to be treated as a parent worth inheriting from, so the attributes set on it are ignored when the subclass is created.
In the latter case, the metaclasses conflict in ways I don't fully understand. The docs https://docs.djangoproject.com/en/dev//topics/forms/modelforms/#form-inheritance simply remark "For technical reasons, a subclass cannot inherit from both a ModelForm and a Form simultaneously".
It doesn't seem possible to give the putative mixin class the metaclasses it needs manually to solve this (e.g. __metaclass__ = DeclarativeFieldsMetaclass or __metaclass__ = ModelFormMetaclass.
One solution might be to provide a FormMixin base class for mixins to inherit from.
Another might be to make forms.ModelFormMetaclass.__new__() less discriminating, and allow get_declared_fields() to look at attributes of classes that are not only ModelForms.
Change History (11)
comment:1 by , 13 years ago
| Component: | Uncategorized → Forms |
|---|---|
| Triage Stage: | Unreviewed → Design decision needed |
| Type: | Uncategorized → New feature |
comment:2 by , 13 years ago
| Triage Stage: | Design decision needed → Accepted |
|---|
comment:3 by , 12 years ago
| Has patch: | set |
|---|---|
| Owner: | changed from to |
| Status: | new → assigned |
| Version: | 1.4 → master |
comment:6 by , 12 years ago
| Resolution: | → fixed |
|---|---|
| Status: | assigned → closed |
PR https://github.com/django/django/pull/1382