I'm getting the following data:
{'name_work': 'рациональные числа', 'writing_date': datetime.datetime(2024, 3, 15, 16, 18, 37, tzinfo=datetime.timezone.utc), 'student_type': \<TypeStudentWork: TypeStudentWork object (2)\>, 'number_of_tasks': '10', 'student': \<User: Dear Student\>, 'example': \<Example: ответы к 1 самостоятельной\>, 'teacher': \<SimpleLazyObject: \<User: Diana Berkina\>\>, 'image_work': \<InMemoryUploadedFile: только\_ответы.jpg (image/jpeg)\>}
My views is a class that receives this data and sends it to the form:
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)
print(students)
for student in students:
image_file = request.FILES.get("image_work_" + str(student.id))
if image_file:
initial_data = {
'name_work': type_work_obj.name_work,
'writing_date': type_work_obj.writing_date,
'student_type': type_work_obj,
'number_of_tasks': '10',
'student': student,
'example': type_work_obj.example,
'teacher': request.user,
'image_work': image_file
}
print("Initial data for student", student.username, ":", initial_data)
form = StudentWorkForm(initial=initial_data)
print(form.errors)
if form.is_valid():
form.save()
else:
print("Errors for student", student.username, ":", form.errors)
except Exception as e:
print(e)
return redirect('moderator')
My model is the model of the work I'm trying to keep:
class StudentWork(models.Model):
name_work = models.CharField(max_length=55)
writing_date = models.DateTimeField()
student_type = models.ForeignKey(
TypeStudentWork,
related_name='type_works',
on_delete=models.CASCADE,
blank=True,
null=True
)
number_of_tasks = models.CharField(max_length=5, default="5")
student = models.ForeignKey(
User,
related_name='student',
on_delete=models.SET_NULL,
null=True
)
example = models.ForeignKey(
Example,
on_delete=models.SET_NULL,
null=True
)
image_work = models.ImageField(upload_to='image')
text_work = models.TextField(null=True, blank=True)
proven_work = models.TextField(null=True, blank=True)
assessment = models.CharField(max_length=10, null=True, blank=True)
teacher = models.ForeignKey(
User,
related_name='teacher',
on_delete=models.SET_NULL,
blank=True,
null=True
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(blank=True, null=True)
I've tried extracting id into fields where the type is ForeignKey. But as I understand I need objects, I don't know how to get them correctly.