Home > database >  Django boundfields auto naming: changing the form part
Django boundfields auto naming: changing the form part

Time:10-27

I can't seem to find if/how this is possible. But say I have a 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 renders, 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.

Is there a way to specify that prefix?

CodePudding user response:

Okay, so in short:

  • Subclass BaseInlineFormset
  • add {"prefix":"foo"} to the kwargs in init & pass that on
  • Magic

For instance:

class MyBaseInlineFormset(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        kwargs["prefix"] = "foo"
        super().__init__(*args, **kwargs)

Then your inlineformset declaration be like:

DetPoFormset = inlineformset_factory(Ap_entcmd, Ap_detcmd, form=Detform, formset=MyBaseInlineFormset, can_delete=True, extra=0)

Then your management form input (id_XXX-TOTAL_FORMS etc.) will be like:

<input type="hidden" name="foo-TOTAL_FORMS" value="0" id="id_foo-TOTAL_FORMS">

as well as all the tags in the formset.

  • Related