1

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 class="topnav">
            {% for st in stages %}
                <div class="dropdown">
                    <button class="dropbtn">{{st.stage_name}}</button>
                    <div class="dropdown-content">
                        {% for qs in questions %}
                            {% if qs.stage_id == st.id %}
                                <a href="#">{{qs.question_name}}</a>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            {% endfor %}
        </div>
    </body>
Noobie
  • 21
  • 4
  • Maybe it will help https://stackoverflow.com/questions/16790375/django-object-is-not-json-serializable#:~:text=156-,simplejson%20and%20json,-don%27t%20work%20with – Сергей Кох Sep 29 '22 at 19:52
  • Thank you, i´ll try it , but still there must be more simple solution for thing like that. – Noobie Sep 29 '22 at 20:01

1 Answers1

1

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 class="dropdown">
        <button class="dropbtn">{{st.name}}</button>
        <div class="dropdown-content">
            {% for qs in st.get_questions %}
              <a href="#">{{qs.name}}</a>
            {% endfor %}
        </div>
    </div>
{% endfor %}
Noobie
  • 21
  • 4
ANFAS PV
  • 293
  • 2
  • 13
  • Thanks it works, only there is no longer needed if loop ({% if qs.stage_id == st.id %}) in html. – Noobie Sep 30 '22 at 08:14