我有一个非常简单的表格
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})
答案 0 :(得分:1)
查看您的request.POST
,satisfied_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)