7

我正在关注本教程并进行了一些更改:http ://www.jacobian.org/writing/dynamic-form-generation/ ,所有这些我将在下面作为片段发布。当我尝试访问通过我的动态表单视图的页面时,它会引发 TypeError。这是回溯:http ://dpaste.com/793196/ 。

forms.py(测试/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)

view.py (测试/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) 

任何帮助将不胜感激,因为我正在努力寻找答案。

4

1 回答 1

33

你不小心忘记了逗号。

super(TestForm, self).__init__(*args, **kwargs)
于 2012-08-29T16:30:24.383 回答