I am trying to pass a value from views.py to forms.py in django
views.py:
def pods(request):
clusterName = request.GET.get('data') ----> this is the value I want to pass to forms
return render(request,'pods.html',{"nodeForm":forms.getPodsOnNodes()})
forms.py:
class getPodsOnNodes(forms.Form):
nodeName = forms.ChoiceField(label='Node Name',choices=functions.choiceMaker(functions.nodesList(**this is where I want to use clusterName from views**)))
Would you please let me know how I can do this?
CodePudding user response:
Considering to get the data from post request passing it to html
form = getPodsOnNodes(request.POST)
if form.is_valid():
clusterName = request.POST["data"]
return render(request, 'pods.html', context={'nodeForm': form, 'variable_name': clusterName})
CodePudding user response:
You can pass variables to your form from the view by calling the form with kwargs :
def pods(request):
clusterName = request.GET.get('data') ----> this is the value I want to pass to forms
return render(request,'pods.html',{"nodeForm":forms.getPodsOnNodes(clusterName)})
And in your form, you need to retrieve the value of your kwarg in your __init__
method (before the inherited one or else you'll get an error because of an undefined kwarg). However you'll then need to define your field inside of the __init__
method as else your nodeName
variable won't be defined.
So your form class will become like that:
class getPodsOnNodes(forms.Form):
def __init__(self, *args, **kwargs):
nodeName = kwargs.pop('nodeName')
super().__init__(*args, **kwargs)
self.fields['nodeName'] = forms.ChoiceField(label='Node Name',choices=functions.choiceMaker(functions.nodesList(nodeName)))