复选框为true或false时如何更新

时间:2019-09-27 09:27:11

标签: html django

模板

  {% for me in student %}
 <input type='checkbox' name="check[0]" value="1" {% if me.Asthma  %} checked="check"  {% endif %} /> Ashtma
 </td></tr><tr valign='top'><td>
<input type='checkbox' name="check[0]" value="1"  {% if me.CongenitalAnomalies  %}checked="check" {% endif %} /> Congenital Anomalies
 </td></tr><tr valign='top'><td>
<input type='checkbox' name="check[0]" value="1" {% if me.ContactLenses  %}checked="check" {% endif %}  /> Contact Lenses
 </td></tr><tr valign='top'><td>
 {% endfor %}

观看次数

  asthma = request.POST.get('check[0]')
  congenitalAnomalies = request.POST.get('check[0]')
  Contact = request.POST.get('check[0]')
  update.Asthma=asthma
  update.CongenitalAnomalies=congenitalAnomalies
  update.ContactLenses = Contact

模型

  Asthma=models.BooleanField(null=True, blank=True)
  CongenitalAnomalies=models.BooleanField(null=True,blank=True)
  ContactLenses=models.BooleanField(null=True,blank=True)

如果我不检查所有内容,但我检查了一个自动检查所有项目,则可以正常工作,请更正我的代码,

1 个答案:

答案 0 :(得分:0)

为模板中的name元素使用唯一的<checkbox>属性:

{% for me in student %}
 <input type='checkbox' name="asthma" value="1" {% if me.Asthma  %} checked="check"  {% endif %} /> Ashtma
 </td></tr><tr valign='top'><td>
<input type='checkbox' name="congenital_anomalies" value="1"  {% if me.CongenitalAnomalies  %}checked="check" {% endif %} /> Congenital Anomalies
 </td></tr><tr valign='top'><td>
<input type='checkbox' name="contact-lenses" value="1" {% if me.ContactLenses  %}checked="check" {% endif %}  /> Contact Lenses
 </td></tr><tr valign='top'><td>
 {% endfor %}

然后,您还必须在视图中使用正确的名称:

asthma = request.POST.get('asthma')
congenitalAnomalies = request.POST.get('congenital_anomalies')
Contact = request.POST.get('contact-lenses')
update.Asthma=asthma
update.CongenitalAnomalies=congenitalAnomalies
update.ContactLenses = Contact

请注意,这仅在您仅更新视图中的一个对象时才有效。如果您视图中的代码片段实际上处于循环中,则必须将对象的ID添加到名称中。

<input type='checkbox' name="asthma-{me.id}" value="1" {% if me.Asthma  %} checked="check"  {% endif %}

for update in students:
    asthma = request.POST.get(f'asthma-{update.id}')
    ...

话虽这么说,Django带有非常强大的form handling,它可以使您的生活更加轻松。