没有通过form.is_valid来处理django视图中的表单

时间:2014-08-11 19:39:03

标签: django django-forms django-views

我根据问题ID填写以下表格:

class QuestionForm(forms.Form):
    options = forms.ModelMultipleChoiceField(queryset=Option.objects.none(), 
                                    widget=forms.RadioSelect)

    def __init__(self, *args, **kwargs):
        question_id = kwargs.pop('question_id', None)
        if question_id:
            print question_id
            super(QuestionForm, self).__init__()
            question = Question.objects.get(pk=question_id)
            ts = Option.objects.filter(question = question)
            for t in ts:
                print t.name
            self.fields['options'].queryset = Option.objects.filter(question = question)

    def clean(self):
        print 'in clean'
        cleaned_options = self.cleaned_data['options']
        try:
            print cleaned_options
            raise forms.ValidationError('That is not the right answer.  Try again.')
        except:
            return cleaned_options 

我从我的观点中这样称呼它:

if request.method == "POST":
        print 'in post'
        form = QuestionForm(request.POST, question_id=question.id)
        print '---'
        options = request.POST.getlist('options')
        option = options[0]
        print option
        if form.is_valid():
            print '******'

我的模板看起来像这样:

<form action="" method="post">
    {% csrf_token %}
    {{ form }}
    {{ form.errors }}
    <br />
    <button type="submit">Save</button>
</form>

我得到了我选择的选项,但是我无法触发干净方法来提醒用户是否选择了正确的答案。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的__init__方法存在许多问题。

导致你实际问题的是你没有将args和kwargs传递给超类方法。因此表单数据从未实际分配,因此is_valid永远不会成立。你应该这样做:

super(QuestionForm, self).__init__(*args, **kwargs)

同样重要的是,超级调用不应该在if语句中缩进。无论发生什么,你都需要打电话。这里最简单的解决方法是将其移至if

之前