Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda