对不起,我是初学者。如何将变量/值x =“ ABCDE”传递给表单?
#views.py
...
x = "ABCDE"
form1 = KSS_Form1(initial={'x':x})
context = {'form':form1, **context}
return render(request, 'af/size/01_kss_size2.html', context)
#forms.py
class KSS_Form1(forms.Form):
mat_geh_innen = forms.ChoiceField(choices=[], widget=forms.Select())
def __init__(self, *args, **kwargs):
super(KSS_Form1, self).__init__(*args, **kwargs)
self.initial['mat_geh_innen'] = x
self.fields['mat_geh_innen'].choices = \
[(i.id, "Housing: " + i.mat_housing.descr) \
for i in afc_select_housing_innenteile.objects.filter(Q(series__valuefg__exact=x) & Q(anw_01=True))]
目前,我收到一条错误消息
Exception Value: name 'x' is not defined
如果表单中有许多不同的ChoiceField,如何传递2、3或更多的值?
谢谢
答案 0 :(得分:1)
您可以从self.initial
字典中获得此信息:
#forms.py
class KSS_Form1(forms.Form):
mat_geh_innen = forms.ChoiceField(choices=[], widget=forms.Select())
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['mat_geh_innen'].initial = self.initial['x']
self.fields['mat_geh_innen'].choices = [
(i.id, 'Housing: ' + i.mat_housing.descr)
for i in
afc_select_housing_innenteile.objects.filter(series__valuefg=x, anw_01=True)
]
但是,您可能希望使用ModelChoiceField
[Django-doc],以便更轻松地选择模型对象。
答案 1 :(得分:0)
Willem Van Onsem,谢谢您的提示。 对我来说,这就是解决方案。
TestSuite.Test-1.Step 1
TestSuite.Test-1.Step 2
...