1

我正在尝试使用 django modelformset_factory 在 django 中创建学生考勤表...但是当我保存表单集时,我的 id 无效这是我的实现

我有两个模型,一个 StudentAttendance 和 StudentClass: 1:StudentAttendance 模型负责存储学生
出勤数据这里是示例

class StudentAttendance(models.Model):
  classroom_id = models.ForeignKey(ClassRoom,   on_delete=models.CASCADE, related_name='student_attendance')
 attendance_date = models.DateField()
 student_id = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='student_attendance')
 status = models.CharField(max_length=20, choices=ATTENDANCE_CHOICES)
 comment = models.CharField(max_length=150, blank=True)
#signed_by = models.ForeignKey(Teacher, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return str(self.student_id)

2:StudentClass模型是一个子模型,将一个学生映射到他各自的班级

class StudentClass(models.Model):
"""
This is a bridge table to link a student to a class
when you add a student to a class we update the selected class capacity

"""
main_class = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name='class_student')
academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE)
student_id = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='student_class')

@property
def is_current_class(self):
    if self.academic_year.is_current_session:
        return True
    return False

def __str__(self):
    return str(self.student_id)

所以我的 forms.py 实现是:

class StudentsAttendanceForm(forms.ModelForm):
class Meta:
    model = StudentAttendance
    fields = ('status', 'comment')
    #exclude = [
        #'siqned_by',
    #]

在我的views.py上:

def student_attendance_manager(request):
"""
this function is responsible for querying the attendance parameters and present the student multiple attendance form
"""
if request.method == "POST":
    # get the class name , the attendance date  and present the attendance form

    class_name = get_object_or_404(ClassRoom, pk=request.POST['class_name']) # class name
    attendance_date = request.POST['date_field'] # date

    # get the students in the class which is current active
    student = StudentClass.objects.filter(main_class=request.POST['class_name'])

    # modelform creation
    AttendanceFormSet = modelformset_factory(StudentAttendance, form=StudentsAttendanceForm, extra=0)

    # initiate the form and pass in the required parameters ie: classroom_id, attendance_date
    list_formset = AttendanceFormSet(queryset=student)

    # initialise the class_name and attendance date
    #for form_inst in list_formset:
        #form_inst.fields['classroom_id'].initial = class_name
        #form_inst.fields['attendance_date'].initial = attendance_date

    template = 'attendance/students_attendance_form.html'

    context = {
        'class_name':class_name,
        'attendance_form': list_formset,
    }

    return JsonResponse({'html_form': render_to_string(template, context, request=request)})

template = 'attendance/students_attendance_manager.html'
class_date_selector_form = ClassroomDateQueryForm(request.GET or None)
context = {
    'choice_form':class_date_selector_form
}
return render(request, template, context)

当用户发布要提交的表单时,这就是我处理表单的方式:

def student_attendance_register(request):
if request.method == "POST":
    students = StudentClass.objects.filter(main_class=request.GET['class_id'])
    StudentsAttendanceFormSet = modelformset_factory(StudentAttendance, form=StudentsAttendanceForm, extra=0)
    list_formset = StudentsAttendanceFormSet(request.POST, queryset=students)
    if list_formset.is_valid():
        list_formset.save()
        return HttpResponse('valid')
    else:
        return HttpResponse(list_formset.errors)

在我的模板上,我在表格中显示表单,这是我的实现:form.html:

 <form class="js-mark-attendance" method="post"  action="{% url 'attendance:student_attendance_register' %}?class_id={{ class_name.id }}">
    {% csrf_token %}
    <table class="table-striped table table-bordered" id="Student_attendance_table">
        <thead>
        <tr>
            <th>#</th>
            <th>Admission Number</th>
            <th>Name</th>
            <th>Status</th>
            <th>Comment</th>
        </tr>
        </thead>
        <tbody>
        {{ attendance_form.management_form }}
        {% for form_inst in attendance_form %}
        {% for hidden in form_inst.hidden_fields %}
            {{ hidden }}
        {% endfor %}
                <tr>
                    <td>{{ forloop.counter }}</td>
                    <td>{{ form_inst.instance.student_id.admission_number }}</td>
                    <td>{{ form_inst.instance.student_id }}</td>
                    <td>{{ form_inst.status }}</td>
                    <td> {{ form_inst.comment }}</td>
                    {{ form_inst.classroom_id.as_hidden }}
                    {{ form_inst.attendance_date.as_hidden }}
                    {{ form_inst.student_id.as_hidden }}


                </tr>
        {% endfor %}
        </tbody>
    </table>
    <div class="row">
        <div class="col-md-12 d-flex justify-content-center">
            <input type="submit" value="Mark Attendance" class="btn btn-success">
        </div>
    </div>
</form>

这是用户点击提交按钮后 django 抛出的错误:

id

Select a valid choice. That choice is not one of the available choices.

所以我的问题是......我该如何处理这个帖子请求表,或者如果他们是完成我的任务的另一种方式:任何潜在客户都将受到重视

4

1 回答 1

0

哎呀......我发现我的问题是modelsfomset_factory的错误使用......

于 2020-02-12T12:13:01.353 回答