我使用ForiegnKey创建了一个与父模型相关的子模型。在forms.py中,我使用ModelChoiceField,其中queryset = Parent.objects.all& widget = RadioInput。在我的模板中,我有一个行表。渲染模板时,它返回每行中的整个查询集,因为{{form.post}}返回整个查询集。如何按行列出每个对象?
Models.py:
class Parent(models.Model):
parent_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
from1 = models.CharField(max_length=20)
class Child(models.Model):
child_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
parent = models.ForeignKey(Parent, default=1, related_name='childs' )
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, unique=False)
amount = models.IntegerField()
forms.py:
class ChildForm(forms.ModelForm):
parent = forms.ModelChoiceField(queryset= Parent.objects.all(), label="Parent", widget=forms.RadioSelect(), initial=0)
amount = forms.IntegerField(help_text='Place the child for a Parent')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(ChildForm, self).__init__(*args, **kwargs)
self.fields['parent'].queryset = Parent.objects.all()
模板:
{% for parent in parent_queryset %}
<table class="table table-striped, sortable">
<thead>
<tr>
<th>Load No.</th>
<th>From</th>
</tr>
</thead>
<tbody>
<tr> // HOW CAN I LIST THE PARENT'S OBJECTS AS PER ROW??
<td >{{form.parent}}</td>
<td>{{ parent.from1 }}</a><br/></td>
</tr>
</tbody>
</table>
<table class="table table-striped, sortable " style="margin-top: 10px">
<thead>
<tr>
<th> Amount</th>
</tr>
</thead>
<tbody>
<tr>
<form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
<td>{% render_field form.amount class="form-control" %}</td>
</tr>
</tbody>
</table>
<input type='submit' value='Post Child'/></form>
{% endfor %}
答案 0 :(得分:0)
您可以循环浏览模板中的相关字段,如下所示:
{% for child in parent.childs.all %}
{{ child.user }}
{{ child.amount }}
{% endfor %}