У меня есть модельная форма. Когда я отправляю данные, нажимая кнопку отправки, данные не сохраняются. Я проверил, действительны ли мои формы. Я обнаружил, что 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>
Я проверил все, но не нашел ошибок.
models.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)
forms.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)
views.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
}
)