【发布时间】:2020-09-16 06:42:43
【问题描述】:
我想用动态生成的 ChoiceField 选项实现一个 Django 表单。
在我的 views.py 中,我定义了以下(相关)方法:
from .forms import OptionForm
def get_choice():
return # like this [(q.optionA, q.optionA), (q.optionB, q.optionB), (q.optionC, q.optionC), (q.optionD, q.optionD)]
# how can I pass q to this __init__ method
class OptionForm(forms.Form):
options= forms.ChoiceField(choices= [])
def __init__(self, *args, **kwargs):
super(OptionForm, self).__init__(*args, **kwargs)
self.fields['options'].choices = get_choice()
def viewtest(request, test_pk):
# get the test object containing all the questions
# each question contains four options using which I want to generate ChoiceField options corresponding to each question
# each option is available as q.optionA, q.optionB q.optionC & q.optionD
test= get_object_or_404(Test, pk= test_pk)
options= []
for q in test.questions.all():
opform= OptionForm() # how do I pass q.optionA, q.optionB q.optionC & q.optionD here to dynamically provide ChoiceField options?
options.append(opform)
return render(request, 'tests/test.html', {'test': test, 'options': options})
【问题讨论】:
标签: python python-3.x django django-models django-forms