8 years after, the accepted answer will not work.
For example to render custom form fields in MyInlineForm
in the following setup in Django-2.2.3
:
class MyInlineAdmin(admin.StackedInline):
model = MyInlineModel
form = MyInlineForm
@admin.register(MyModelAdmin)
class MyModelAdmin(admn.ModelAdmin):
inlines = (MyInlineAdmin,)
Inspired from @santhoshnsscoe, this can be achieved by overriding ModelFormMetaclass.__new__
:
Solution 1:
from django.forms.models import ModelFormMetaclass
class MyModelFormMetaclass(ModelFormMetaclass):
def __new__(cls, name, bases, attrs):
for field in ['test_1', 'test_2', 'test_3']:
attrs[field] = forms.CharField(max_length=30)
return super().__new__(cls, name, bases, attrs)
class MyInlinelForm(forms.ModelForm, metaclass=MyModelFormMetaclass):
class Meta:
model = MyInlineModel
fields = '__all__'
Reviewing the relevant code, ModelFormMetaclass
inherits from DeclarativeFieldsMetaclass
where attrs
are passed to declared_fields
of the form:
for key, value in list(attrs.items()):
if isinstance(value, Field):
current_fields.append((key, value))
attrs.pop(key)
attrs['declared_fields'] = OrderedDict(current_fields)
Based on this observation, and following the relevant docs of ModelAdmin.get_formsets_with_inlines
I tried to enrich the declared_fields
using that method of ModelAdmin
and it also worked:
Solution 2:
class MyInlineForm(forms.ModelForm):
class Meta:
model = MyInlineModel
fields = '__all__'
class MyInlineAdmin(admin.StackedInline):
model = MyInlineModel
form = MyInlineForm
@admin.register(MyModelAdmin)
class MyModelAdmin(admn.ModelAdmin):
inlines = (MyInlineAdmin,)
def get_formsets_with_inlines(self, request, obj=None):
for inline in self.get_inline_instances(request, obj):
if isinstance(inline, MyInlineAdmn):
for field in ['test_1', 'test_2', 'test_3']:
inline.form.declared_fields[field] = forms.CharField(max_length=30)
yield inline.get_formset(request, obj), inline