django mutlipleChoiceField如何验证?

时间:2011-05-16 20:38:55

标签: python django django-forms

我的表格如下:

forms.py:

class enrolForm(forms.Form):
    CHOICES = [('male','male'),('female','female')]
    students = forms.MultipleChoiceField(choices = CHOICES)

views.py:

 form = enrolForm(request.POST)
 if form.is_valid():
            print "creating student"
            exam = models.Exam.objects.get(name=examName)
            .
            .#more code .......

它永远不会到达(print "creating student"),表格永远不会有效。这是为什么 ? 我如何验证这样的表格请帮助

编辑: 它在form.errors中说:<ul class = "errorlist"><li> students<ul class="errorlist"><li>This field is required.</li></ul></li></ul><br> 编辑:

views.py:

def enrol(request,examName):
    print "EXAm naaame"
    form = enrolForm()
    allStudents = models.User.objects.filter(groups__name="students")
    myList = []

    for i in allStudents:
        myList.append((i,i))


    print allStudents,'33333333333333333333'

    form.fields['students'].choices = myList


    if request.method == 'POST':
        form = enrolForm(request.POST)

        if form.is_valid():
            exam = models.Exam.objects.get(name=examName) 
            for i in form.cleaned_data['students']:

                user= models.User.objects.get(username=i)
                exam = models.Exam.objects.get(name= examName)                
                models.Exam_Student.objects.create(user,exam)

            return render_to_response('enrol.html',RequestContext(request,{'form':form}))

    variables = RequestContext(request,{'form':form})
    return render_to_response("enrol.html",variables)

2 个答案:

答案 0 :(得分:1)

使用标准ChoiceField有什么问题?

class enrolForm(forms.Form):
    CHOICES = [('male','male'),('female','female')]
    students = forms.ChoiceField(choices = CHOICES)

此操作还可以查看错误并告知我们有用:

if form.is_valid():
    print "creating student"
    exam = models.Exam.objects.get(name=examName)
    ...
else:
    print 'ERRORS:', form.errors

答案 1 :(得分:1)

您的表单无效,因为students字段是必需的。这意味着您必须选择一名学生才能使is_valid()成为现实。

编辑:由于某些奇怪的原因,我无法在评论中添加新行,所以我在这里添加...

出于测试目的,除去必需品之外的所有内容,看看会发生什么:

def enrol(request):
    if request.method == 'POST':
        form = enrolForm(request.POST)
        if form.is_valid():
            print 'Valid form'
        else:
            print form
    else:
        form = enrolForm()

    return render_to_response('enrol.html', {'form' : form}, context_instance=RequestContext(request))