Home > OS >  Django forloop inside forloop in Template
Django forloop inside forloop in Template

Time:09-30

hello iam trying to make Dropdown Menu in Navbar with querysets. I was trying to make it with two querysets send to html template ( "stages","questions") that are related to each other by key (id , stage_id), but i cant figured out why forloops cant work together. My second try was with passing data in json to javascript and make it with js QuerySelector, but django querysets are not JSON serializable. Any suggestions how to make it please ?

views.py

def edit_pages(request, gameid):
    stages = Stage.objects.filter(game_id=gameid)
    print(stages)
    questions = []
    for st in stages:
        questions = chain(questions,Question.objects.filter(stage_id=st.id))
    print(questions)
        
    return render(request, "homeSuperuser/edit_pages.html",{'stages': stages, 'questions': questions})

html

<body>
        <div >
            {% for st in stages %}
                <div >
                    <button >{{st.stage_name}}</button>
                    <div >
                        {% for qs in questions %}
                            {% if qs.stage_id == st.id %}
                                <a href="#">{{qs.question_name}}</a>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            {% endfor %}
        </div>
    </body>

CodePudding user response:

Define a model method as follows

class Stage(models.Model):
    name = models.CharField(max_length=128)

    def get_questions(self):
        return Question.objects.filter(stage=self)

    def __str__(self):
        return str(self.name)


class Question(models.Model):
    stage = models.ForeignKey(Stage, on_delete=models.PROTECT, related_name="questions")
    name = models.CharField(max_length=128)

    def __str__(self):
        return str(self.name)

Now you can loop them in the template as follows

{% for st in stages %}
    <div >
        <button >{{st.name}}</button>
        <div >
            {% for qs in st.get_questions %}
              <a href="#">{{qs.name}}</a>
            {% endfor %}
        </div>
    </div>
{% endfor %}
  • Related