Home > Mobile >  define an element as default value in a list created by a for loop in a django template
define an element as default value in a list created by a for loop in a django template

Time:09-22

here is my html

<div class="modal-body">
    <form action="#" id="periodeOptionForm">
        <div class=" card-body">
            <div class="form-group form-elements">
                <div class="form-label">Options</div>
                    <div class="custom-controls-stacked">
                        {% for periode in periodes %}
                            <label class="custom-control custom-radio" id'{{periode.labelle}}'>
                                <input type="radio" class="custom-control-input" name="example-radios" value="{{periode.valeur}}">
                                <span class="custom-control-label">{{periode.labelle}} </span>
                            </label>
                    {% endfor %}
                </div>
            </div>
        </div>
    </form>
</div>

My fbv

def periodes(request):
    ...
    periodes = [{"labelle":"10 minutes","valeur":10},{"labelle":"30 minutes","valeur":30},{"labelle":"1 heure","valeur":60}]
    ....
    return render(request,"my_template.html",{"periodes":periodes}

When I display the html page no elements are selected. I want the first element of my periodes list to be selected by default. How can I do it?

CodePudding user response:

You can use forloop.first around checked:

<input type="radio" class="custom-control-input" name="example-radios" value="{{periode.valeur}}" {% if forloop.first %}checked{% endif %}>
  • Related