我很难在我的 django formset 中实现初始数据。
就上下文而言,我正在构建一个出勤应用程序,其中存在学生列表并且需要每天评估出勤率。
我想要做的是让管理员点击上面列出日期的链接。然后,他们将被带到数据网格,其中每一行代表系统中的学生人数以及 4 列(学生姓名、日期、出席/缺席下拉菜单、备注字段)。目标是让学生姓名字段预填充学生模型中的学生列表,日期字段预填充用户单击链接上的日期,出勤和备注字段是用户输入。
任何帮助将非常感激
谢谢!
——</p>
Student model
class Student(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
GENDER_CHOICES = (
('male', 'male'),
('female', 'female'),
)
gender = models.CharField(max_length=12, choices=GENDER_CHOICES, null=False, blank=False)
date_of_birth = models.DateField(auto_now=False, auto_now_add=False)
@property
def full_name(self):
return ''.join([self.first_name, '_', self.last_name])
def __unicode__(self):
return self.full_name
Attendance model
class Attendance(models.Model):
student = models.ForeignKey('students.Student')
attendance_date = models.DateField(auto_now=False, auto_now_add=False)
STATUS_CHOICES = (
('present', ‘1’),
('absent', ‘0’),
)
status = models.CharField(max_length=12, choices=STATUS_CHOICES, null=False, blank=False)
notes = models.CharField(max_length=300, null=True, blank=True)
class Meta:
unique_together = ("student", "attendance_date")
def __unicode__(self):
return self.student
Attendance form
class AttendanceForm(forms.ModelForm):
class Meta:
model = Attendance
fields = ["student","attendance_date", "status", "notes"]
View
def add_attendance(request):
s = Student.objects.all().values()
AttendanceFormSet = formset_factory(AttendanceForm, extra=0)
formset = AttendanceFormSet(request.POST or None, initial=s)
if formset.is_valid():
try:
instance = form.save(commit=False)
instance.save()
return HttpResponseRedirect('/')
except:
return HttpResponseRedirect('/')
context = {
"formset": formset,
}
return render(request, "group_attendance.html", context)
Template
<table id="formset" class="form">
{{ formset.management_form }}
{% for form in formset.forms %}
{% if forloop.first %}
<thead><tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr></thead>
{% endif %}
<tr>
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>