Django pass / param variable to formform formset

I was digging and I can not find the answer to my problem.

Basically, if you want to pass parameters / variables to a form, you will do this:

class SomeForm(ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        my_arg = kwargs.pop('my_arg')
        super(SomeForm, self).__init__(*args, **kwargs)

And pass param like this in the views:

def someview(request):
    form = SomeForm(request.POST, my_arg=somevalue)
    if request.method == 'POST':
        ...
    else:
        form = SomeForm(my_arg=somevalue)

     return render(....)

However, I use inlineformset_factory, and I get an error message:

__init__() got an unexpected keyword argument 'my_arg'

If I try to pass it like this:

myformset = inlineformset_factory(modelA, modelB, form=SomeForm, extra=1, can_delete=True)

def someview(request):
    form = myformset(request.POST, my_arg=somevalue)
    if request.method == 'POST':
        ...
    else:
        form = SomeForm(my_arg=somevalue)

     return render(....)

I am using django-dynamic-formset to dynamically create my forms (django 1.8)

Am I missing something, or am I doing it wrong? If so, would that be a plausible solution?

UPDATE

I tried to do

class BaseFormSet(BaseInlineFormSet):

    def __init__(self, *args, **kwargs):
        self.my_arg = kwargs.pop("my_arg")
        super(BaseFormSet, self).__init__(*args, **kwargs)

then adding formset = BaseFormSetto:

myformset = inlineformset_factory(modelA, modelB, formset = BaseFormSet, form=SomeForm, extra=1, can_delete=True)

until I get the error form BaseFormSet, how do I get my_argin SomeForm? And I also get the error message:

KeyError at /someurl
'my_arg'

    Request Method: GET
    Request URL:    http://localhost:8000/
    Django Version: 1.8.2
    Exception Type: KeyError
    Exception Value: 'my_arg'
    Exception Location: ..../forms.py in __init__, line 108(the my_arg = kwargs.pop('my_arg') line)
    Python Executable:  C:\Python27\python.exe
    Python Version: 2.7.10
    Python Path:    
    ['C:\\Users\\lolwat\\Desktop\\ITSWEBSITE',
     'C:\\Windows\\system32\\python27.zip',
     'C:\\Python27\\DLLs',
     'C:\\Python27\\lib',
     'C:\\Python27\\lib\\plat-win',
     'C:\\Python27\\lib\\lib-tk',
     'C:\\Python27',
     'C:\\Python27\\lib\\site-packages']

I didn’t change anything from my code except adding BaseFormSet

+4

Source: https://habr.com/ru/post/1629436/


All Articles