django - 如何使用数据库查询结果预填充表单集表单数据?

django - How can I prefill formset forms data using database query result?

我正在创建一个学生出勤表,其中需要根据教师在一种表格中选择学生 class 从学生模型中获取学生姓名、学生 class 和 ID 的详细信息。我已经尝试通过在查询数据上使用 for 循环来使用 initial 来预填充表单集中的表单,但是它只为一条记录填充数据。下面是 forms.py、模型和 views.py 的代码。有人可以帮忙吗

forms.py

class student(models.Model):
    studentid = models.AutoField(primary_key=True)
    Gender = models.CharField(max_length=6, choices=gender, null=True)
    Name = models.CharField(max_length=100, null=True)
    DOB = models.DateField(null=True)
    Image = models.ImageField(null=True, upload_to='images')
    Status = models.CharField(max_length=10, choices=statchoice, null=True)
    Father_name = models.CharField(max_length=100, null=True)
    Mother_name = models.CharField(max_length=100, null=True)
    Address = models.CharField(max_length=200, null=True)
    Contact_no = models.IntegerField(null=True)
    Email = models.EmailField(null=True)
    Admission_class = models.CharField(max_length=40, null=True, choices=grade)
    Admission_date = models.DateField(null=True)
    Current_class = models.CharField(max_length=40, null=True, choices=grade)
    Leaving_date = models.DateField(null=True, blank=True)
    objects = models.Manager() 
    def __str__(self):
        return str(self.studentid)  

class student_attendance(models.Model):
    Student_ID = models.CharField(max_length=100, null=True)
    Student_Name = models.CharField(max_length=100, null=True)
    Student_class = models.CharField(max_length=100, null=True, choices=grade)
    Attendance_date = models.DateField(null=True, auto_now_add=True, blank=True)
    Attendance_status = models.CharField(choices=attendance, null=True, max_length=10)
    objects = models.Manager() 

Views.py

def student_attend(request):
if request.method == 'POST':
    data = request.POST.get('studentGrade')
    formset_data = student.objects.filter(Current_class=data)
    AttendanceFormSet = formset_factory(std_attendance, extra=(len(formset_data))-1)
    for element in formset_data:
        formset = AttendanceFormSet(initial=[
            {'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"}
        ])
    param = {'formset':formset} 
    return render(request, 'home/student_attendance.html', param)     
return render(request, 'home/student_attendance.html')

form.py:

class student_register(ModelForm):
class Meta:
    model = student
    fields = '__all__'

class std_attendance(ModelForm):
class Meta:
    model = student_attendance
    fields = '__all__'

循环中的每次迭代都会覆盖表单集,这就是为什么只填充一个表单的原因,您需要以这种方式用循环内的所有表单填充参数:

initial = []
for element in formset_data:
        initial.append({'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"}
        
formset = AttendanceFormSet(initial=initial)