无法检索复选框 POST 数据,form.is_valid() returns false

Cannot Retrieve Checkbox POST Data, form.is_valid() returns false

我是 Django/Python 的初学者,每当我尝试提交表单时 is_valid() 方法 returns 错误。我尝试使用 form.errors 显示错误,但 returns 什么也没有或 {}。当我尝试 运行 以下代码时:

form.non_field_errors()
field_errors = [(field.label, field.errors) for field in form]

我得到[('', []), ('Required', [])]

form.py

class ApplicationForm(forms.ModelForm):
email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput(
    attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), )
required = forms.ModelMultipleChoiceField(queryset=Requirements.objects.all(), widget=forms.CheckboxSelectMultiple)

class Meta:
    model = Requirements
    fields = ['email', 'required']

views.py

def application_form(request):
try:
    form = ApplicationForm()
    context = {'form': form}

    if request.method == 'GET':
        return render(request, 'requirements/job_specs.html', context)
    if request.method == 'POST':
        print(form.is_valid(), form.errors)
        if form.is_valid():
            form.save()
            return JsonResponse({'created': True})
    form.non_field_errors()
    field_errors = [(field.label, field.errors) for field in form]
    print(field_errors)
    return JsonResponse(form.errors.as_json(), safe=False)
except Exception as e:
    print(e)

form = ApplicationForm(request.POST or None)
context = {'form': form}
return render(request, 'requirements/job_specs.html', context)

HTML

<form method="POST" id="application-form">
                {% csrf_token %}

                {{ form }}

                <div class="bg-light row" >
                    <div class="" id="btn-box">
                        <div class="col-md-12 d-grid gap-2 col-6 ">
                            <button type="submit" class="btn btn-primary btn-lg">Save</button>
                        </div>
                    </div>
                </div>

            </form>

我曾尝试应用 or 等类似帖子的解决方案,但 none 帮助解决了问题。任何帮助将不胜感激

在查看了几个小时的代码后,我终于发现了它的问题所在。我只需要在 form = ApplicationForm() 中添加 request.POST or None,它就像一个魅力。