[英]Django: Dynamically generate ChoiceField values from another model object
我想用动态生成的 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})
要从模型中获得选择, ModelChoiceField
是更好的选择。 在此处查找更多详细信息: https : //docs.djangoproject.com/en/3.1/ref/forms/fields/#django.forms.ModelChoiceField
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.