简体   繁体   中英

Hide and show elements inside Django HTML template

I have 2 buttons orders , and suppliers ., and want to show data in a Django web app when the corresponding button is clicked. To do this my home.html looks like

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $(".button_order").click(function(){
          $(".myorders").show();
          $(".mysupplier").hide();
        });
        $(".button_supplier").click(function(){
            $(".myorders").hide();
            $(".mysupplier").show();
        });
      });
</script>

syle.css looks like;

.myorders,
.mysupplier{
font-size: 25px;
display: none;
}

This works perfectly fine until I use normal data like;

<body>
    {%block content %}
    <button class="button_order" >ORDERS</button>
    <button class="button_supplier" >SUPPLIER</button>
    <p class="myorders" >
       This is my order
    </p>
    <p class="mysupplier">
       my supplier is cool
    </p>
</body>

But when I try to use data into <p class="mysupplier"> or <p class="myorders" > from my databases, the hide property no longer works, like below part.

<p class="myorders">
    {% for element in orders  %}
    {% for key,val in element.items %}
    <ul><li>{{key}}:{{val}}</li></ul>
    {% endfor %}
    <hr class="new1">
    {% endfor %}
</p>

I should get Order data from database only when ORDER button is clicked, but my server shows all data from before without even clicking the button. How to maintain hide and show the property of my data.

my views.py looks like

from django.shortcuts import render
client = MongoClient("mongodb://localhost:27017/")
db=client.inventory_data
def home(request):
    collection_data_1 = db['orders']
    orders = list(collection_data_1.find())
    collection_data_2= db['suppliers']
    suppliers = list(collection_data_2.find())
    return render(request,'home.html',{'orders': orders,'suppliers':suppliers})

The loop in template is executed when rendering template. You pass all your data from view to template. if you just want to hide it from display add to your js:

<script>
    $(document).ready(function(){
        $(".mysupplier").hide();
        $(".myorders").hide();
        $(".button_order").click(function(){
          $(".myorders").show();
          $(".mysupplier").hide();
        });
        $(".button_supplier").click(function(){
            $(".myorders").hide();
            $(".mysupplier").show();
        });
      });
</script>

but if you would like to dynamicly fetch current data from db by pressing button i recommend use htmx ( htmx.org )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM