Formet, inlineformset_Factory and kwargs

I have a couple of models that can be called their model A and model B. There is a foreign key from A to B.
That is, the power between A and B is 1: n.

I created an appropriate ModelForm for B called MF_B. I have an extra field that I define in B. for example.

class MF_B(forms.ModelForm):

    stuff = forms.MultipleChoiceField(queryset=None, required=False)

    class Meta:
        model=B

as follows from the above code, I want to populate the selection here with a set of queries. (I omitted the override code in init (), which we will use to set the set of queries in the material field)

The deal is that I want to use inlineformset_factory to create a form with A and several forms with B on one page.

I just wanted to pass a bunch of new kwargs to inlineformset_factory, but he continued to complain about unexpected keyword arguments, and, looking at the backend code in django, I understand why: inlineformset_factory does not accept custom kwargs. it accepts only kwargs values ​​defined in the sig method.

def inlineformset_factory(parent_model, model, form=ModelForm,
                          formset=BaseInlineFormSet, fk_name=None,
                          fields=None, exclude=None,
                          extra=3, can_order=False, can_delete=True, max_num=None,
                          formfield_callback=None):

I don't think ican uses formfield_callback because I need to pass self.request.user to filter objects that return to the query set.

any suggestions?

+3
source share
1 answer

To limit the MultipleChoiceField to the request you specify, you must use a factory. In this case, it will be inlineformset_factory_factory, which is a bit confusing, but for example:

in form.py (or similar)

def make_inlineformset_factory(queryset, xmodel):
    """
    Returns an Inlineformset factory for the given queryset . . .
    """
    class My_inlineformset_factory():
        stuff = forms.ModelChoiceField(queryset=queryset)
        class Meta:
            model = xmodel
    return My_inlineformset_factory

, , : django: ? Inlineformset_factory.

, , .

0

All Articles