Is it safe to modify `base_fields` on admin form classes?

The forms API documentation warns against changing a Form’s base_fields attribute:

Beware not to alter the base_fields attribute because this modification will influence all subsequent ContactForm instances within the same Python process: …

Could someone tell me if this also holds for ModelFormMetaclass subclasses that are used in the admin?

For example, the class returned by ModelAdmin.get_form() comes from a modelform_factory, so I expect base_fields can be safely modified here. Is that correct?

Is this explained somewhere in the docs?

Thanks in advance.

I’m curious - I’m not sure I understand why you would want to modify base_fields at that point. Once you’ve gotten an instance of the form to use, you can modify the fields. What is it that you are looking to accomplish by this that modifying fields isn’t going to do for you?
(And sorry, no, I don’t have an immediate answer for your question.)

… Once you’ve gotten an instance of the form to use, you can modify the fields. …

@KenWhitesell Thanks for the quick reply.

A use case would be e.g. extending ModelAdmin.get_form() to modify the admin form’s fields dynamically, based on the object being edited.

At this point, we only have access to the base_fields, because ModelAdmin.get_form() returns a class, not an instance (see source).

However, regardless of the use case, I would like to know if the warning from the forms API docs, concerning base_fields, extends to the admin form classes.

I suppose it doesn’t, as the admin form classes are factory generated, but I’m not 100% sure, and I don’t like nasty surprises. :slight_smile:

This is not an xy-problem: I’m aware of several alternative ways to achieve this, e.g. using self.instance in the __init__() of a custom ModelForm, or getting the object based on the pk from the request in a formfield_for_* method, but those are not always convenient.

While it’s not a definitive answer, I have tried the example in the docs with using two different instances of the same form class created by the modelform_factory function, and the problem does not appear. If I create two forms from the same form class from the same output of modelform_factory, the problem does occur as documented.

So I agree with your supposition - I cannot see where that warning would apply in this case.

1 Like

@KenWhitesell That’s good to hear. Thanks for the effort! Much appreciated. :slight_smile: