Python Django将变量/参数传递到modelform formset
我一直在四处寻找,似乎找不到问题的答案 基本上,如果要将参数/变量传递给表单,请执行以下操作:Python Django将变量/参数传递到modelform formset,python,django,django-forms,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(re
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\u factory中的,我得到一个错误:
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']
\uuuu init\uuuuuuuuuuuu()得到一个意外的关键字参数“my\u 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 1.8)
我是错过了什么还是做错了?如果是这样,什么才是合理的解决方案
更新
我试过了
class BaseFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
self.my_arg = kwargs.pop("my_arg")
super(BaseFormSet, self).__init__(*args, **kwargs)
然后将formset=BaseFormSet
添加到:
myformset = inlineformset_factory(modelA, modelB, formset = BaseFormSet, form=SomeForm, extra=1, can_delete=True)
虽然我没有收到错误表单BaseFormSet
,但如何将my_arg
发送到某个表单?我也得到了一个错误:
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
我是从中得到这个想法的。找到解决方案了吗?如果为pop添加一个默认值,即self.my_arg=kwargs.pop(“my_arg”,无)
?