如何从视图中更改表单变量值

时间:2011-05-06 09:51:03

标签: python django

我一直在尝试从我的视角向以下表单发送数据。

我需要变量(选项)在每次调用此表单时更改

class AnswersForm(forms.Form):

question  = forms.RadioSelect
CHOICES=[('sf','asdf')]
radioButton = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

question = forms.RadioSelect CHOICES=[('sf','asdf')] radioButton = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

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)

问题是:我需要来自表单类的变量(CHOICES)来更改它在视图类中的值(我知道我可以使用CHOICES = [('b','a')])但我想要从视图中更改它,因为此代码仅用于显示问题)

任何更好的想法?

提前致谢

1 个答案:

答案 0 :(得分:2)

您可以更改覆盖表单 init 方法的字段选项(以便它接受选择参数),也可以根据需要在init之后更改字段的选择。

First Case会是这样的:

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

查看示例:

form_instance = AnswersForm(new_choices)