Actually, I think this relates directly to another thread from just a couple days ago - Creating Model Form with python code in form - #8 by KenWhitesell
(Now, while I could hypothesize the possibility of creating a formset consisting of different forms, perhaps using the
get_form_kwargs
parameter to create a formset in an ABABABAB pattern, I’ve never seen it done and I have no idea what problems would be encountered along the way.)
This fits into the category of different forms in a formset, and clearly there is some “friction” involved here.
Now, in the simplified case, given a trivial model form:
class SomeModelForm(forms.ModelForm):
class Meta:
model = SomeModel
fields = '__all__'
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', None)
super().__init__(*args, **kwargs)
When this form is instantiated, the variable instance
will have the instance of the model associated with it.
If you then modify self.fields
after the super()
call in __init__
, you can make your desired changes.
This means if you then have:
SomeModelFormset = modelformset_factory(SomeModel, form=SomeModelForm, extra=0)
some_model_formset = SomeModelFormset(...)
You will have generated your desired forms.
Edit: I was wrong here.
Validation is not performed until something else happens causing the validation to be performed, such as calling is_valid
. It does not happen during __init__
.