I'm writing a mixin class to dynamically add extra fields to a ModelForm which sublasses it.
The new fields are generated in the mixin's __init__
method. See bellow:
mixin class code (strongly shortened & simplified):
class ForeignFieldsMixin(object):
# …
def __init__(self, *args, **kwargs):
# …
instance = kwargs.get('instance')
self.fields[extra_field_name] = fields_for_model(fmodel, (fldname,))
# ^^^^^^ here a new field instance is added
self.fields[extra_field_name].initial = 'some value'
# ^^^^^^ here is set an inital value for the new field
# …
However form's class still refuses to list the new field name in its Meta.fields
:
class ContactAdminForm(ForeignFieldsMixin, forms.ModelForm):
# …
class Meta:
model = Contact
fields = ('title', 'extra_field_name',)
and fails with the following exception
File "../lib/python2.7/site-packages/django/forms/models.py", line 215, in __new__
raise FieldError(message)
FieldError: Unknown field(s) (extra_field_name) specified for Contact
I do suspect ModelForm's
metaclass (or of some of its ancestors) at the time of class definition ie. before classes are instantiated raises this exception as it not yet knows about new field names added.
I do not know if I'm taking this from the wrong side as the documentation is rather sparse in this area. I would really like avoid monkey-patching of ModelForm's
metaclass.
Is there some other way how to simulate the basic in-code fields definition to satisfy Django's class model with its metaclasses protectors but do it dynamically with a generally applicable class/function ?