pythondjangocheckboxdjango-formsdjango-templates

Django template - set checkbox checked if object.val == true


I'm junior backend dev. I don't know how to use JS.

I can't set

<input type="checkbox" name="player_check"> 

true... or reverse i can't set

<input type="checkbox" name="player_check" checked>

false.

My code:

<table id="some_table">
    <thead>
    <tr>
        <th>Prepared</th>
    </tr>
    </thead>
    <tbody>
    {% for player in players %}
        <tr>
            <td>
                <input type="checkbox" name="player_check">
            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>

Let's say in 'players' I have 5 players, each player has a value "player_check".

Two of them have:

player.player_check = True

Rest:

player.player_check = False

I'm trying to initiate checkbox in my table with these values using {{}} or {% %}

I've tried:

<input type="checkbox" name="player_check" value=1>
<input type="checkbox" name="player_check" value="1">
<input type="checkbox" name="player_check" value="True">
<input type="checkbox" name="player_check" value=True>
<input type="checkbox" name="player_check" value="checked">

Nothing works... Then i found that checkbox has a parametr checked so:

<input type="checkbox" name="player_check" checked> 

That was ok BUT... now i cant turn it off:

<input type="checkbox" name="player_check" checked="false">
<input type="checkbox" name="player_check" checked="0">
<input type="checkbox" name="player_check" checked=0>
<input type="checkbox" name="player_check" checked="unchecked">

So i decided to use django templpates + change in python code: Now player.player_check equals checked or unchecked

It still doesn't work! Now i can't put {{ }} without name like "something"={{ foo }}

Now i have 0 ideas what i can do more to make it work... Maybe JS? but i cant believe there is no right way to do it just in django/python. ;/


Solution

  • You can do this with for example an {% if ... %} tag:

    {% for player in players %}
    <tr>
      <td>
      <input type="checkbox" name="player_check"{% if player.player_check %} checked{% endif %}>
      </td>
    </tr>
    {% endfor %}

    But I think you better use Django forms, which will handle this in a more elegant way for you: you specify the form field, and Django will handle the rest.