我似乎无法弄清楚为什么它不让我显示我传递给模板上的表单的ForeignKey字段。我一直在研究,但无法找到有效解释的答案。任何人都有任何想法,我做错了什么?
forms.py
class MeetingForm(forms.ModelForm):
meeting_date = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Date.objects.all())
person = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Person.objects.all())
class Meta:
model = MeetingAttendance
fields = ['meeting_date', 'person', 'attended',]
Models.py
class MeetingAttendance(models.Model):
meeting_date = models.ForeignKey('Date', on_delete=models.CASCADE)
person = models.ForeignKey('Person', on_delete=models.CASCADE)
attended = models.BooleanField()
def __str__(self):
return "%s - %s" % (self.person, self.meeting_date)
Views.py
def date_detail(request, slug):
people = Person.objects.all()
detail = Date.objects.get(slug=slug)
MeetingFormSet = formset_factory(MeetingForm, extra=len(people)-2, max_num=len(people))
if request.method == "POST":
form = MeetingFormSet(request.POST)
if form.is_valid():
formset = form.save(commit=True)
formset.save()
return redirect('date_detail', slug=slug)
else:
initial_data = [{'person': person, 'meeting_date': detail} for person in people]
form = MeetingFormSet(initial=initial_data)
context = {
'form': form,
'people': people,
}
return render(request, 'date_detail.html', context)
模板
<div class="directory panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Meeting Details</h3>
</div><!-- end paneil-heading -->
<div class="panel-body">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
</div>
</div>