Search code examples
djangofor-loopjinja2nested-loops

Nested for loop in django template not showing correct output


So i have this loop which is showing the correct output when i print it in my views.py file

for x in list4:
        print x[0]
        for y in x[3]:
            print y[1]
        print "\n"

output:

test question edited
test1
test2
test3


test question
hello
hello12
hkjhjkh
hjk
hkjhkj


another test
sdfsdf
sdfsdf


test2
sdfsd
sdfsd


another
sdfsdf
fsdfsd
sdf
sdfsd
fsd

but while running the same loop in django template to show the values in the form it shows repeated output

test.jinja2 code

{% extends "base.jinja2" %}
{% block content %}
{% block body %}





        {% for x in ques %}
            <form class='form-horizontal' method=POST action="/test-portal/student/test/">
            <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">






                        <div class="form-group">

                            <input type="hidden" name="id" value={{x.0}}>
                            <label for="ques_title" class="col-sm-2 control-label" name='ques_title'>{{x[0]}}</label>
                        </div>

                        {% for y in x[3] %}
                            <!-- {% for b in y %} -->

                                <div class="form-group">
                                    <div class="col-sm-2">
                                <!-- <input type='checkbox' name='flag' id="new" value={{x}}> -->
                                        <label for="option" class="col-sm-2 control-label" name='ques_title'>{{y[1]}}</label>
                                    </div>
                                </div>
                            <!-- {% endfor %} -->
                        {% endfor %}



        {% endfor %}
                    <div class="form-group">
                        <button type="submit" class="btn btn-default" name='button' value='submit'>SUBMIT</button>
                        <!-- <td><button type="submit" class="btn btn-default" name='button' value='options'>ADD OPTIONS</button></td> -->

                    </div>

            </form>



{% endblock %}
{% endblock %} 

output of the template

test question edited
test1
test1
test1
test1
test2
test2
test2
test2
test3
test3
test3
test3

test question
hello
hello
hello
hello
hello12
hello12
hello12
hello12
hkjhjkh
hkjhjkh
hkjhjkh
hkjhjkh
hjk
hjk
hjk
hjk
hkjhkj
hkjhkj
hkjhkj
hkjhkj

another test
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf

test2
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd

another
sdfsdf
sdfsdf
sdfsdf
sdfsdf
fsdfsd
fsdfsd
fsdfsd
fsdfsd
sdf
sdf
sdf
sdf
sdfsd
sdfsd
sdfsd
sdfsd
fsd
fsd
fsd
fsd

Solution

  • As stated by @alfonso.kim the problem was the comment, as django was still considering the commented for loop to be an actual loop so by removing

    <!-- {% for b in y %} -->
    <!-- {% endfor %} -->
    

    the code works fine.