代码之家  ›  专栏  ›  技术社区  ›  Atma

django表单中带有客户参数的键错误

  •  0
  • Atma  · 技术社区  · 11 年前

    我有以下表格:

    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)
            super(QuestionForm, self).__init__(*args, **kwargs)
    
            if question_id:
                print question_id
    
                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'
            #this is the last thing to print before failing
            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 '******'
                print form
            else:
                print '######'
                print form.errors
    

    我的模板如下所示:

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

    我在模板中使用表单的行中得到一个关键错误:

    enter image description here

    似乎抛出错误的行是:

    cleaned_options = self.cleaned_data['options']
    
    2 回复  |  直到 11 年前
        1
  •  1
  •   brain storm    11 年前

    你永远不会返回 HttpResponse 在你看来。

    试试看:

    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 '******'
                print form
                return HttpResponseRedirect('/admin/')
     else:
         form=QuestionForm()
         return render(request,'myapp/form.html',{'form':form})
    
        2
  •  1
  •   Aaron Lelevier    11 年前

    当覆盖 clean() 方法,您应该使用 super() 。这将调用的继承功能 clean() 。因此,您的表单应该如下所示:

    class QuestionForm(forms.Form):
        # for logic
        def clean(self):
            super(QuestionForm, self).clean()
            # get the initial 'cleaned_data' Dict from the form
            cleaned_data = self.cleaned_data
            # clean it however you wish, just make sure to return it at the end of clean()
            return cleaned_data
    

    正如上面所说的“脑风暴”,观点必须回归 Http Responses .