首页 > 解决方案 > 表单在 django 模板中给出验证错误

问题描述

我有一个模型。当我提交数据时,按下提交按钮,数据没有保存。我检查了我的表格是否有效。我发现 EducationForm 无效。它有一些错误。打印education_form错误,我发现了这些错误。 <ul class="errorlist"><li>institution_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>degree<ul class="errorlist"><li>This field is required.</li></ul></li><li>passing_year<ul class="errorlist"><li>This field is required.</li></ul></li><li>result<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

我检查了所有内容,但找不到任何错误。

模型.py:

    class Education(models.Model):
        """
        Stores employee education background
        """
        employee = models.ForeignKey('Employee', related_name='edu_employee', on_delete=models.CASCADE, null=True)
        institution_name = models.CharField(max_length=128, null=True)
        degree = models.CharField(max_length=128, null=True)
        passing_year = models.DateField(null=True)
        result = models.DecimalField(max_digits=5, decimal_places=2, null=True)
        @receiver(post_save, sender=Employee)
        def create_or_update_employee_work_experience(sender, instance, created, **kwargs):
             if created:
                  Education.objects.create(employee=instance)

表格.py:

class EducationForm(forms.ModelForm):
    """
    Creates a form for saving educational info of an employee
    """
    class Meta:
        model = Education
        fields = [
            'institution_name',
            'degree',
            'passing_year',
            'result',
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

视图.py:

class EmployeeAddView(LoginRequiredMixin,CreateView):
    """
    Creates new employee
    """
    login_url = '/authentication/login/'
    template_name = 'employee/employee_add_form.html'
    form_class = EmployeeAddModelForm
    work_form_class = WorkExperienceForm
    education_form_class = EducationForm
    queryset = Employee.objects.all()

    def form_valid(self, form):
        print(form.cleaned_data)
        return super().form_valid(form)

    # Override default get method
    def get(self, request, *args, **kwargs):
        form = self.form_class()
        work_form = self.work_form_class()
        education_form = self.education_form_class()

        return render(request, self.template_name, {
                                                    'form': form,
                                                    'work_form': work_form,
                                                    'education_form': education_form
                                                    }
                                                )

    # Override default post method
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        work_form = self.work_form_class(request.POST, prefix='work_form')
        education_form = self.education_form_class(request.POST, prefix='education_form')

        if form.is_valid() and work_form.is_valid() and education_form.is_valid():
            instance = form.save()
            work = work_form.save(commit=False)
            education = education_form.save(commit=False)
            work.employee = instance
            education.employee = instance
            work.save()
            education.save()

        if not education_form.is_valid():
            print(education_form.errors)
            return redirect('employee:employee-list')

        return render(request, self.template_name, {
                                                    'form': form,
                                                    'work_form': work_form,
                                                    'education_form': education_form
                                                    }
                                                )

标签: pythonhtmldjangotemplates

解决方案


推荐阅读