Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
What do I need to do if I want to use database data conditionally in Django templates?

I am working on an ecommerce store in Django. I want to know that how do I use the database data passed to templates using render() method, conditionally through JavaScript or AJAX or JSON?

For example, let's say I have a following models.py:

from django.db import models

class Suit(models.Model):
    title = models.CharField(max_length = 100, verbose_name = "Title")
    img = models.FileField(upload_to = 'suit-products/', null = True, verbose_name = "Picture")

    def __str__(self):
        return f"{self.title}"

class Buttoning(models.Model):
    title = models.CharField(max_length = 100, verbose_name = "Title")
    img = models.FileField(upload_to = 'buttonings/', null = True, verbose_name = "Picture")

    def __str__(self):
        return f"{self.title}"

and following views.py

from django.shortcuts import render

def index(request):
    suit_prods             = Suit.objects.all()
    buttoning = Buttoning.objects.all()

    context {
        "suit_prods": suit_prods,
        "buttoning": buttoning
    }

    return render(request, "index/index.html", context)

and following index.html (template):

    {% for element in suit_prods %}
        <li>
            <a href="#">
                <div id="menu">
                    <img src="{{ element.img.url }}" />
                    <span>{{ element.title }}</span>
                    <span></span>
                </div>
            </a>
        </li>
    {% endfor %}

Now what I want is, if the clicked element in the list items in index.html has the title as "two_piece_suit" then show items of {{ buttoning }} as a list, otherwise pass.

If I explain it more using some JS syntax, then I want following kind of behaviour:

<scrip>
    var suit_menu = document.getElementsByClassName("menu");
    for(var i = 0; i < suit_menu.length; i++) {
        if(suit_menu.text == "two_piece_suit") {
            {% for element in buttoning %}
                <li>
                    <a href="#">
                        <div id="buttoning">
                            <img src="{{ element.img.url }}" />
                            <span>{{ element.title }}</span>
                            <span></span>
                        </div>
                    </a>
                </li>
            {% endfor %}
        }
    }
</script>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If I understand correctly, you don't necessarily need JavaScript to achieve this. Also, <script> is missing a t, and your for loop doesn't seem to add the HTML to the document at all.

You can achieve that purely with the Django Template Language by integrating the buttons for loop with an if condition like this:

{% if element.title == 'two_piece_suit' %}
    {% for button in buttoning %}
        <Some HTML>{{ button.title }}</Some HTML>
    {% endfor %}
{% endif %}

That way, the list of buttons is only displayed if the title is two_piece_suit.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda