根据数据库值Django选择要检查的单选按钮

时间:2019-03-18 07:14:39

标签: python django

我有一个html表,它是根据数据库中的值填充的。

如何设置表单加载时从数据库值中选择哪个单选按钮。我已经尝试了下面的代码,但它没有检查任何内容。谢谢

<table class="table table-bordered table-hover table-sm">
                <thead class="thead-light">
                    <tr>
                        <th scope="col"><h4>Id</h4></th>
                        <th scope="col"><h4>Requirement Name</h4></th>
                        <th scope="col"><h4>Remarks</h4></th>
                        <th scope="col"><h4>Date Promised</h4></th>
                        <th scope="col"><h4>Completed</h4></th>
                    </tr>
                </thead>

                <tbody>
                    {% for req in requirements %}
                    <tr>
                        <th><input type="hidden" name="requirements_id_{{req.pk}}" value="{{ req.pk }}"><span>{{ req.pk }}</span></th>
                        <th><span>{{ req.requirement }}</span></th>
                        <th><textarea rows="1" cols="35" name="requirements_remarks_{{req.pk}}">{{ req.remarks }}</textarea></th>
                        <th><input type="date" name="requirements_date_promised_{{req.pk}}" value="{{ req.date_promised|date:'Y-m-d' }}"></th>
                        <th><input type="radio" name="requirements_completed_{{req.pk}}" value="{{ req.completed }}"> No
                            <input type="radio" name="requirements_completed_{{req.pk}}" value="{{ req.completed }}"> Yes</th>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>

1 个答案:

答案 0 :(得分:0)

要在不使用Django表单的情况下设置选择哪个单选按钮,可以对设置checked属性的每个单选按钮应用一些逻辑。请注意,您还应确保value属性对于每个元素都是唯一的:

<th><input type="radio" name="requirements_completed_{{req.pk}}" value="no"{% if not req.completed %} checked{% endif %}> No
    <input type="radio" name="requirements_completed_{{req.pk}}" value="yes"{% if req.completed %} checked{% endif %}> Yes</th>