我正在按照本教程进行一些更改:http://www.jacobian.org/writing/dynamic-form-generation/,我将在下面将其作为片段发布。当我尝试访问通过动态表单视图的页面时,它会抛出TypeError。这是追溯:http://dpaste.com/793196/。
forms.py(testing / forms.py)
from django import forms
class TestForm(forms.Form):
test_id = forms.CharField()
user_id = forms.CharField()
complete_time = forms.IntegerField()
def __init__(self, *args, **kwargs):
extra = kwargs.pop('extra')
super(TestForm, self).__init__(*args **kwargs)
for i, question in enumerate(extra):
self.fields['custom_%s' % i] = forms.CharField(label=question)
def extra_answers(self):
for name, value in self.cleaned_data.items():
if name.startswith('custom_'):
yield (self.fields[name].label, value)
views.py(testing / views.py)
def exam(request, test_id):
user = request.user
t = get_object_or_404(Test, pk=test_id)
if user.is_authenticated():
extra_questions = get_questions(request, test_id)
if request.method == 'POST':
form = TestForm(request.POST or None, extra=extra_questions)
if form.is_valid():
for (question, answer) in form.extra_answers():
save_answer(request, question, answer)
return HttpResponseRedirect('/tests/')
else:
form = TestForm(None, extra=extra_questions)
return render(request, 'testing/exam.html', { 't' : t, 'form' : form })
else:
return HttpResponseRedirect('/')
def get_questions(request, test_id):
t = get_object_or_404(Test, pk=test_id)
questions = t.question_set.all()
for question in questions:
title = question.question
qlist = []
qlist.append(title)
任何帮助都会受到赞赏,因为我正忙着回答。
答案 0 :(得分:15)
你不小心忘记了逗号。
super(TestForm, self).__init__(*args, **kwargs)