django form: how to check out checkbox state in template

前端 未结 4 1690
情话喂你
情话喂你 2021-02-06 14:46

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

相关标签:
4条回答
  • 2021-02-06 15:10

    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%}

    0 讨论(0)
  • 2021-02-06 15:11

    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.

    0 讨论(0)
  • 2021-02-06 15:15

    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 %}
    
    0 讨论(0)
  • 2021-02-06 15:16

    In models.py:

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

    In the template:

     <input type="checkbox" name="published" {% if article.published %}checked{% endif %} />
    
    0 讨论(0)
提交回复
热议问题