Image не проходит валидацию

Картинка не проходит валидацию. Мы получаем картинку из request. Мои данные:

<MultiValueDict: {'image_work_4': [<InMemoryUploadedFile: только_ответы.jpg (image/jpeg)>], 'image_work_2': [<InMemoryUploadedFile: задание_от_7_до_8.jpg (image/jpeg)>]}>

Но я получаю ошибку что поле image обязательно для заполнения. Когда я передаю следующие данные:

Initial data for student 1 : {'name_work': 'рациональные числа', 'writing_date': datetime.datetime(2024, 3, 15, 16, 18, 37, tzinfo=datetime.timezone.utc), 'student_type': 2, 'number_of_tasks': '10', 'student': 4, 'example': 1, 'teacher': 1, 'image_work': <InMemoryUploadedFile: только_ответы.jpg (image/jpeg)>}
Errors for student 1 : <ul class="errorlist"><li>image_work<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Initial data for student 1 : {'name_work': 'рациональные числа', 'writing_date': datetime.datetime(2024, 3, 15, 16, 18, 37, tzinfo=datetime.timezone.utc), 'student_type': 2, 'number_of_tasks': '10', 'student': 2, 'example': 1, 'teacher': 1, 'image_work': <InMemoryUploadedFile: задание_от_7_до_8.jpg (image/jpeg)>}
Errors for student 1 : <ul class="errorlist"><li>image_work<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

Мой views класс:

class CreateStudentWorkView(View):

def post(self, request, type_work_id):
    try:
        type_work_obj = TypeStudentWork.objects.get(pk=type_work_id)
        students = User.objects.filter(student_class=type_work_obj.school_class)

        for student in students:
            print(request.FILES)
            initial_data = {
                'name_work': type_work_obj.name_work,
                'writing_date': type_work_obj.writing_date,
                'student_type': type_work_obj.id,
                'number_of_tasks': '10',
                'student': student.id,
                'example': type_work_obj.example.id,
                'teacher': request.user.id,
                'image_work': request.FILES.get("image_work_" + str(student.id))
            }
            print("Initial data for student", student.username, ":", initial_data)
            form = StudentWorkForm(initial_data)
            if form.is_valid():
                form.save()
            else:
                print("Errors for student", student.username, ":", form.errors)
    except Exception as e:
        print(e)
    return redirect('moderator')

мой html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Students</title>
</head>
<body>
    <h1>All Students</h1>
    <form action="{% url 'create_work' type_work.id %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <table>
            <thead>
                <tr>
                    <th>Фамилия</th>
                    <th>Имя</th>
                    <th>Добавить работу</th>
                </tr>
            </thead>
            <tbody>
                {% if students %}
                    {% for student in students %}
                    <tr>
                        <td>{{ student.last_name }}</td>
                        <td>{{ student.first_name }}</td>
                        <td>
                            <input type="file" name="image_work_{{ student.id }}">
                            <input type="hidden" name="student_id_{{ student.id }}" value="{{ student.id }}">
                        </td>
                    </tr>
                    {% endfor %}
                {% else %}
                    <tr>
                        <td colspan="3">Нет учеников в данном классе</td>
                    </tr>
                {% endif %}
            </tbody>
        </table>
        <div class="button-container">
            <button type="submit" class="save-button">Сохранить работы</button>
        </div>
    </form>

</body>
</html>

Форма сохраняет данные, если поле image прописать не обязательным к заполнению. По этому уверена, что не так именно с этим полем. Но не могу понять почему данные которые я передаю не валидны.

Вернуться на верх