我正在尝试使用表单向导,但我无法确定在哪里设置字段的选择。
#views.py
class QuizWizard(SessionWizardView):
def done(self, form_list, **kwargs):
return render_to_response('done.html', {
'form_data':[form.cleaned_data for form in form_list],
})
#forms.py
class QuestionForm(forms.ModelForm):
#selection = forms.ChoiceField()
class Meta:
model = Question
我看到一个空表单,看起来像是用于添加对象的管理面板。 我希望能够将问题传递给表单,并填写问题字段,不可编辑,最好不要提交。
如果我这样做
(r'^(?P<quiz_id>\d+)', QuizWizard.as_view(get_form_list)),
函数get_form_list没有长度
(r'^(?P<quiz_id>\d+)', QuizWizard.as_view(get_form_list(quiz_id))),
Quiz_id未知。
所以现在我试图将quiz_id传递给view函数并生成要在表单向导中使用的问题表单列表
url(r'^(?P<quiz_id>\d+)', 'quiz.views.get_form_list'),
class QuizWizard(SessionWizardView):
def done(self, form_list, **kwargs):
return render_to_response('done.html', {
'form_data':[form.cleaned_data for form in form_list],
})
def get_form_list(request, quiz_id):
quiz = Quiz.objects.get(id=quiz_id)
question_forms = []
for question in quiz.questions.all():
choices = []
for choice in question.choices.all():
choices.append(choice)
f = QuestionForm(instance=question)
question_forms.append(f)
return QuizWizard.as_view(question_forms)(request)
我收到错误消息
issubclass() arg 1 must be a class
根据Rohan的回答更新:
def get_form_list(request, quiz_id):
quiz = Quiz.objects.get(id=quiz_id)
question_forms = []
for question in quiz.questions.all():
choices = []
for choice in question.choices.all():
choices.append(choice)
f = QuestionForm(instance=question)
question_forms.append(f)
inst_dict = {}
for idx, question in enumerate(question_forms):
inst_dict[str(idx)] = question
print inst_dict
#inst_dict = { str(index(x)) : x for x in question_forms}
QuestFormList = []
for i in range(len(question_forms)):
QuestFormList.append(QuestionForm)
QuizWizard.as_view(QuestFormList, instance_dict=inst_dict)(request)
使用此代码我收到错误
'ModelFormOptions' object has no attribute 'many_to_many'
这是我的models.py
class Choice(models.Model):
choice = models.CharField(max_length=64)
def __unicode__(self):
return self.choice
#create a multiple choice quiz to start
class Question(models.Model):
question = models.CharField(max_length=64)
answer = models.CharField(max_length=64)
choices = models.ManyToManyField(Choice)
module = models.CharField(max_length=64)
def __unicode__(self):
return self.question
class Quiz(models.Model):
name = models.CharField(max_length=64)
questions = models.ManyToManyField(Question)
def __unicode__(self):
return self.name
答案 0 :(得分:1)
您应该使用类而不是对象来调用它。所以将你的电话改为
QuizWizard.as_view(question_forms)(request)
更新
向导视图将表单类列表作为参数而不是表单实例。您正在question_forms
中创建表单实例并将其传递给查看。
如果要在每个步骤中传递表单的实例,可以传递instance_dict
。
有点像...
inst_dict = { '0': question_forms[0], #step 0 instance
'1': question_forms[1], #step 1 instance
}
QuestFormList = [QuestionForm, QuestionForm ...]
QuizWizard.as_view([QuestFormList, instance_dict=inst_dict)(request)