Reputation: 311
Sorry, I am a beginner. How to pass the variable / value x = "ABCDE" to the form?
#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))]
as for now I get an error message
Exception Value: name 'x' is not defined
How shall I pass 2, 3, or more values if I have a number of different ChoiceFields in the Form?
Thank you
Upvotes: 1
Views: 1890
Reputation: 311
Willem Van Onsem, thank you for the hint. For me this was the solution.
class KSS_Form1(forms.Form):
mat_geh_innen = forms.ChoiceField(choices=[], widget=forms.Select())
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
x = 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)
]
Upvotes: 1
Reputation: 477533
You can obtain this from the self.initial
dictionary:
#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)
]
You however might want to look to a ModelChoiceField
[Django-doc] that makes it more convenient to select model objects.
Upvotes: 2