2011-11-09 66 views
0

我有一個非常簡單的形式布爾字段返回Django中的真實的形式

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 

我要清理這種形式和檢驗在正在used.But出於某種原因 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'] 

試過這種

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}) 
+0

你真的有兩個名稱相同的字段? – second

+0

沒有我的壞...複製錯誤的字段 – Akamad007

+0

你能顯示request.POST的值嗎? –

回答

0

a clean_FOO僅用於清理單個字段,並且應該返回已清理的數據,而不是其他任何內容。

跨越多個領域的驗證,使用clean方法,它應該返回整個cleaned_data字典

看到the docs更多

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> 
+0

即使上述是真實的,它仍然在改變它後返回true。 – Akamad007

+0

你能否更新'request.POST'的值,並告訴我們你的模板? – Alasdair