I’m sure this can be done, but somehow I can’t seem to find a reference in the docs or figure it out. Let’s say I have this form:
class Detform(ModelForm):
class Meta:
model = Ap_detcmd
fields = ["foo"]
Formset = inlineformset_factory(ParentModel, ChildModel,
form=Detform,
can_delete=False,
extra=0)
Then in the template this gets rendered, for instance in the management form (or any field):
<input type="hidden" name="ap_detcmd-TOTAL_FORMS" value="0" id="id_ap_detcmd-TOTAL_FORMS">
Since the model of the form is “Ap_detcmd”, then I get #id_ap_detcmd-… as a prefix for all fields. But then I have some javascripts that acts on stuff and I’d like to NOT have to manage a bunch of different #id_XXXXX_. Those formsets are NEVER used on the same page. Yes I know that can be a slippery slop… but still I’d rather uniformize that naming. ANy ways to do this?
Without doing any real research or investigation on this, I’d give adding a prefix
parameter to your inlineformset_factory definition - something like prefix=""
. (Note: I’m winging this - I’m not in a position / location where I can verify this. Try this at your own risk.)
You can also try setting auto_id="id_"
as a parameter.
1 Like
Geez, this is borderline unfair! (It works).
I dove all the way to get BaseModelForm classes but somehow managed to not find it. I messed around with auto_id, but this didn’t work.
class BaseInlineFormset2(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
kwargs["prefix"] = "foo"
super().__init__(*args, **kwargs)
DetPoFormset = inlineformset_factory(Ap_entcmd, Ap_detcmd,
formset=BaseInlineFormset2,
form=Detform,
can_delete=True,
extra=0)
Okay so I’m not sure why I said yesturday this didn’t work - it does. If you’re using inline formset, add this prefix in the kwargs, and it’ll manage itself. I’m guessing that when I tested quickly yesturday, I just have left in m code change to the form definition itself from previous attempts and that prevented it from working properly.
But most definitely, this will properly namespace forms in the formset with a predicatable prefix.