how to change form variable values from view
i've been trying to send data to the following form from my view.
i need the variable (choices ) to change each time we call this form
class AnswersForm(forms.Form):
question = forms.RadioSelect
CHOICES=[('sf','asdf')]
radioButton = forms.ChoiceField(choices=CHOICES, widget=forms.R开发者_运维知识库adioSelect())
view.py :
def exam_attend(request,ExamName,questionNo=0):
if ExamName:
myList = [('b','a')]
forms.AnswersForm.CHOICES=myList
form = forms.AnswersForm()
variabls = RequestContext(request,{'form':form})
return render_to_response('exam_pageAttend.html',variabls)
the problem is : i need the variable (CHOICES) from the form class to change it's value in the view class ( i know i can just use CHOICES = [('b','a')] ) but i want to change it from the view since this code is only to show the problem )
any better ideas ?
thanks in advance
You can change the field choices overriding the form init method (so that it accepts a choice parameter) or you can change the field's choices after the init, depending on your needs.
First Case would be like this:
class AnswersForm(forms.Form):
radioButton = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
def __init__(self, radio_choices= None, *args, **kwargs):
super(AnswersForm, self).__init__(self, *args, **kwargs)
if radio_choices is not None:
self.fields['radioButton'].choices = radio_choices
View example:
form_instance = AnswersForm(new_choices)
精彩评论