Django – Render CheckboxSelectMultiple() widget individually in template (manually)

djangodjango-forms

I have those two models:

models.py

class App(models.Model):
    app_name = models.SlugField(max_length=50)
    options_loaded = models.ManyToManyField(Option)
    created_by = models.ForeignKey(User)

    def __unicode__(self):
        return self.name

class Option(models.Model):
    option_name = models.SlugField(max_length=50)
    condition = models.BooleanField('Enable condition')
    option = models.BooleanField('Enable option1')
    created_by = models.ForeignKey(User)

    def __unicode__(self):
        return self.option_name

I would like to render a form that would look like this, where checkboxes are from different models (first column from the M2M field with CheckboxSelectMultiple() widget), and Option_name could be <a href="/link/">Option_name</a>

enter image description here

Is it possible?

Best Answer

This is my simple solution: render CheckboxSelectMultiple() manually in template

<table>
<thead>
  <tr>
    <td>&nbsp;</td>
    <td>V</td>
    <td>S</td>
  </tr>
</thead>    
{% for pk, choice in form.options.field.widget.choices %}
<tr>
  <td><a href="/link/{{ choice }}">{{ choice }}</a></td>
  <td>
    <label for="id_options_{{ forloop.counter0 }}">
      <input {% for m2moption in model.m2moptions.all %}{% if option.pk == pk %}checked="checked"{% endif %}{% endfor %} type="checkbox" id="id_options_{{ forloop.counter0 }}" value="{{ pk }}" name="options" />
    </label>
  </td>
</tr>
{% endfor %}                
</table>
Related Topic