如何在dajngo中验证表单集

lxkprmvk  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(376)

我正在使用formset将数据输入数据库,但由于某些原因,每当我在终端中进行测试并调用.is_valid()时,它都不会验证。无论我做什么尝试,它都会返回false。下面是my views.py和forms.py中的代码。任何帮助都将不胜感激!


# Advanced Subjects (Advanced Biology)

def form_5_entry_biology_view(self, request):
    current_teacher = User.objects.get(email=request.user.email)
    logged_school = current_teacher.school_number
    students_involved = User.objects.get(school_number=logged_school).teacher.all()
    data = {"student_name": students_involved}
    formset_data = AdvancedStudents.objects.filter(class_studying="Form V", combination="PCB")
    student_formset = formset_factory(AdvancedBiologyForm, extra=0)
    initial = []
    for element in formset_data:
        initial.append({"student_name": element})
    formset = student_formset(request.POST or None, initial=initial)
    print(formset.is_valid())
    context = {
        "students": students_involved,
        "formset": formset,
        "class_of_students": "Form V",
        "subject_name": "Advanced Biology",
    }
    return render(request, "analyzer/marks_entry/marks_entry_page.html", context)

这是我的表格

class AdvancedBiologyForm(forms.ModelForm):
    student_name = forms.CharField()

    class Meta:
        model = ResultsALevel
        fields = ('student_name', 'advanced_biology_1', 'advanced_biology_2', 
                   'advanced_biology_3',)
dgjrabp2

dgjrabp21#

使用前 request.POSTis_valid() 您可能需要检查是否确实存在post请求,或者是否刚刚查看了页面:

def form_5_entry_biology_view(self, request):
    current_teacher = User.objects.get(email=request.user.email)
    logged_school = current_teacher.school_number
    students_involved = User.objects.get(school_number=logged_school).teacher.all()
    data = {"student_name": students_involved}
    formset_data = AdvancedStudents.objects.filter(class_studying="Form V", combination="PCB")

    # Here you are creating the formset using the model
    student_formset = formset_factory(AdvancedBiologyForm, extra=0)

    # Here you are generating your initial data
    initial = []
    for element in formset_data:
        initial.append({"student_name": element})

    # Here you are using the initial data to create pre-populated
    # forms with it using the formset.
    # These forms will be displayed when the page loads.
    formset = student_formset(initial=initial)

    context = {
        "students": students_involved,
        "formset": formset,
        "class_of_students": "Form V",
        "subject_name": "Advanced Biology",
    }

    # But if the user hits the "submit"-Button...
    if request.method == 'POST':
        # ... you don't want to have the formset with your
        # initial data. Instead you want the entries by the user
        # which are transmitted in request.POST to populate the
        # formset forms.
        formset = student_formset(request.POST or None)
        # Now you can validate the formset with the fields which
        # got input the the user; not the "initial" data like in
        # your original code
        if formset.is_valid():
            # This runs formset validation.
            # You can define your own formset validations like
            # you would for models/forms.
            for form in formset:
                # And / Alternatively:
                # you could in theory also add another "if form.is_valid():" in here
                # This would trigger any validation on the
                # model/form; not the validators on the formset.
                form.save()
            return HttpResponseRedirect(...
    return render(request, "analyzer/marks_entry/marks_entry_page.html", context)

否则你可能会打电话 is_valid() 在未绑定的形式上。来自django文档:
如果表单是使用post请求提交的,视图将再次创建一个表单示例,并使用请求中的数据填充它:form=nameform(request.post)。这称为“将数据绑定到表单”(现在是绑定表单)。
基本上,如果一个表单是空的,它就是未绑定的,如果它填充了数据,它会在post后绑定。当你打开一个页面并立即尝试“is_valid()”时,当你检查一个空表单是否有效时,它基本上总是错误的;这可能永远不会发生。
要指出错误,请执行以下操作:

formset = student_formset(request.POST or None, initial=initial)
print(formset.is_valid())

这是无效的。因为初始值不等于用“实”值填充表单字段。因此,它试图用 request.POST or None . 但是你没有一个 if request.method == 'POST': 条件因此,您的代码将在到达代码的最后一行之前运行,这是显示页面的返回语句。这意味着您的代码将进行验证 request.POST or None 甚至在用户看到页面之前。因此,用户不可能已经输入数据并点击提交。这意味着没有post请求,所以它总是 None . 所以你基本上是在打电话 is_valid() 表单中没有字段值,这会导致验证失败。
编辑1:我刚注意到你的 forms.py 你写了:

fields = ('student_name', 'advanced_biology_1', 'advanced_biology_2', 
                   'advanced_biology_3',)

这应该是一个列表:

fields = ['student_name', 'advanced_biology_1', 'advanced_biology_2', 
                   'advanced_biology_3',]

编辑2:修复了错误的变量名编辑3:添加了大量注解以澄清代码中发生了什么编辑4:更清楚地指出了问题的原因。

相关问题