django form: how to check out checkbox state in template

为君一笑 提交于 2019-12-21 05:33:14

问题


I have a form with checkboxes that works fine, but when the user submits the form with errors and my checkbox is checked I need to change div class which holds the checkbox. So I was experimenting with {{ form.mycheckbox.data }} in the template and it says False on page load. Now when user is click on a checkbox and the form has errors, it says on. So I tried:

{{ if form.mycheckbox.data == True }} doesn't work

{{ if form.mycheckbox.data != False }} doesn't work

{{ if form.mycheckbox.data == 'on' }} doesn't work

{{ if form.mycheckbox.data == on }} doesn't work


回答1:


Use {% if form.mycheckbox.value %}. This will evaluate to true if the box is checked. For the opposite behavior, use {% if not form.mycheckbox.value %}.

Note the syntax is {% if ... %}, not {{ if ...}}. Percent-brackets are for commands, double-brackets are for outputting variables.




回答2:


In models.py:

class Article:
    published = BooleanField()
    (...)

In the template:

 <input type="checkbox" name="published" {% if article.published %}checked{% endif %} />



回答3:


Work for me:

{% for foo in form.tags %}
  <label class="publication-tag">
    <input class="publication-tag__checkbox"
      {% if foo.choice_value in foo.value %}checked="checked"{% endif %}
      type="checkbox" 
      name="{{ foo.name }}"
      value="{{ foo.choice_value }}">
{% endfor %}

That:

{% if foo.choice_value in foo.value %}checked="checked"{% endif %}



回答4:


While, first you should use BooleanField in your model, not the CharField. Then, there are two accesses:

  • just put {{form.yourField}} in your template (preferred)

  • or, use {% if form.yourFiled.value %} checked {%endif%}




回答5:


Django templates are evaluated on the server-side.

I think you want to look into JavaScript to check the state of your check boxes. Doing it with the templating language (especially the one included with Django) is a really bad idea.

Any processing / calculation should be done in the view function / class.



来源:https://stackoverflow.com/questions/7326505/django-form-how-to-check-out-checkbox-state-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!