我无法显示具有多个实例对象的内联表单集。我想要所有的列表Owner
和所有它们的内联表单集Pet
,都是一页。
下面的代码有效,但一次调用 1 个所有者对象。有什么建议么?
模型.py
class Teacher(models.Model):
teacher = models.CharField(max_length=300)
class Owner(models.Model):
relevantteacher = models.ForeignKey(Teacher)
owner = models.CharField(max_length=300)
class PetName(models.Model):
relevantowner = models.ForeignKey(Owner)
pet_name = models.CharField(max_length=50)
表格.py
class OwnerForm(forms.ModelForm):
class Meta:
model = Owner
PetNameFormSet = inlineformset_factory(Owner,
PetName,
can_delete=False,
extra=3,
form=OwnerForm)
视图.py
def petname(request, teacher_id):
teacher = get_object_or_404(Teacher, pk=teacher_id)
owners = Owner.objects.filter(relevantteacher=teacher_id)
owner = owners[0]
if request.method == "POST":
petNameInlineFormSet = PetNameFormSet(request.POST, request.FILES, instance=owner)
if petNameInlineFormSet.is_valid():
petNameInlineFormSet.save()
return HttpResponseRedirect(reverse('success'))
else:
petNameInlineFormSet = PetNameFormSet(instance=owner)
context = {'teacher': teacher, 'owner': owner, 'petNameInlineFormSet' : petNameInlineFormSet}
return render(request, 'petname.html', context)
HTML 宠物名.html
{% load url from future %}
<form class="petname_form" action="{% url "petname" teacher.id %}" method="post">{% csrf_token %}
{{ teacher }}
{{ owner.as_table }}
{{ petNameInlineFormSet.as_table }}
</form>
更新
HTML
{% for owner_form in owner_forms %}
<form class="petname_form" action="{% url "petname" teacher.id %}" method="post">{% csrf_token %
{% for o in owners %}
{{o.owner}} has pets:<br/> //owner is the PK of the Owner model
{{ owner_forms.relevantteacher }}
{{ owner_forms.as_table }}
{{ owner_forms.inline_form.as_table }}
{% endfor %}
</form>