Django将变量/ param传递给modelform formset

时间:2016-02-18 19:09:40

标签: python django django-forms

我一直在挖掘,似乎无法找到问题的答案

基本上,如果要将参数/变量传递给表单,请执行以下操作:

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

并在视图中传递这样的参数:

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

     return render(....)

但是我正在使用inlineformset_factory而我收到错误:

__init__() got an unexpected keyword argument 'my_arg'

如果我试图像这样传递它:

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(....)

我正在使用django-dynamic-formset动态生成表单(django 1.8)

我错过了什么或者我做错了吗?如果是这样,那么什么是合理的解决方案?

更新

我试过

class BaseFormSet(BaseInlineFormSet):

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

然后在{/ p>中添加formset = BaseFormSet

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

虽然我没有收到错误表单BaseFormSet,但如何将my_arg转换为SomeForm?而且我也遇到了错误:

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']

除了添加BaseFormSet

之外,我没有更改代码中的任何内容

我从here

得到了这个想法

0 个答案:

没有答案