sumanth
sumanth

Reputation: 781

How to Display object_list of a queryset in a form with ModelChoiceField as each instance in each row?

I have created a Child model related to a Parent model with a ForiegnKey. In forms.py, I use a ModelChoiceField where queryset = Parent.objects.all & widget = RadioInput. In my template i have a table of rows. When rendering the template, it returns the whole queryset in each row because {{form.post}} returns whole queryset. How can I list each object as per row?

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()

Template:

{% 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 %}

Upvotes: 0

Views: 1451

Answers (1)

denvaar
denvaar

Reputation: 2214

You can loop through related fields in your template like this:

{% for child in parent.childs.all %}
  {{ child.user }}
  {{ child.amount }}
{% endfor %}

Upvotes: 0

Related Questions