在django表单中返回为True的布尔字段

时间:2011-11-09 10:44:13

标签: django django-forms

我有一个非常简单的表格

class IcraveSatisfiedForm(forms.Form):
    satisfied_or_not = forms.BooleanField(label="Was your Crave satisfied?")
    satisfier = forms.CharField(label="Satisfier")



    def clean_satisfier(self):
        satisfier = self.cleaned_data['satisfier']
        satisfied = self.cleaned_data['satisfied_or_not']
        if satisfied == True:
          if satisfier !='':
            try:
                user = User.objects.get(username__iexact = satisfier)
            except:
                user = None
            if not user :
                raise forms.ValidationError('The username is not valid')
            else:
                return user
          else:
            return None

我想清理此表单并检查正在使用的值。但出于某种原因 self.cleaned_data ['satisfied_or_not']始终返回True。我究竟做错了什么 ?

编辑:

我也在我看来试过这个

def my_craves(request,crave_id = None):
    craves = Icrave.objects.filter(person = request.user,satisfied_or_not = False)
    if request.method == 'POST':
        if 'satisfied_or_not' in request.POST:
            my_craves_form =IcraveSatisfiedForm(request.POST,user = request.user)
            if my_craves_form.is_valid() :
                satisfied = my_craves_form.cleaned_data['satisfied_or_not']
                satisfier = my_craves_form.cleaned_data['satisfier']

它仍然以True返回

Request.POST

<QueryDict: {u'csrfmiddlewaretoken': [u'21bdde0fdac2b18101e1c42ba2f92843'], u'satisfier': [u'admin'], u'satisfied_or_not': [u'Update']}>

我使用普通表格来渲染数据

 my_craves_form = IcraveSatisfiedForm()
    return render( request, 'icrave/view/my_craves.html', {'craves' : craves,'my_craves_form':my_craves_form})

2 个答案:

答案 0 :(得分:1)

查看您的request.POSTsatisfied_or_not不应该是布尔字段的字符串。

<QueryDict: {u'csrfmiddlewaretoken': [u'21bdde0fdac2b18101e1c42ba2f92843'], u'satisfier': [u'admin'], u'satisfied_or_not': [u'Update']}>  

看起来您可能正在使用名称satisfied_or_not作为表单提交按钮以及复选框。例如:

<p><input type="submit" name="satisfied_or_not" value="Update" /></p>

如果是这样,您需要将其更改为

<p><input type="submit" name="update" value="Update" /></p>

答案 1 :(得分:0)

clean_FOO仅用于清理单个字段,并且应该返回已清理的数据。

要在多个字段中进行验证,请使用clean方法,该方法应返回整个cleaned_data字典

请参阅the docs了解更多