1π
If Iβm understanding this right, I donβt think you need the through table. You should be able to define the ManyToManyField and then use a ModelForm and a CheckboxSelectMultiple widget to display the options as checkboxes.
I changed the models to:
class Container(models.Model):
name = models.CharField(max_length=200)
options = models.ManyToManyField('Option')
# I changed the name of the Checkbox model to Option, for clarity.
class Option(models.Model):
name = models.CharField(max_length=60)
description = models.CharField(max_length=200)
order = models.PositiveSmallIntegerField(default=0)
from forms.py:
class ContainerOptionsForm(forms.ModelForm):
class Meta:
model = Container
fields = ['options']
widgets = {
'options': forms.CheckboxSelectMultiple(),
}
Include the options form field in your template:
{{ form.options }}
If you need more control over the display of the options checkboxes, you can iterate over the options field of the form:
{% for checkbox in form.options %}
<label>{{ checkbox.choice_label }} {{ checkbox.tag }}</label>
{% endfor %}
This should take care of it for a single container on a page. If you need to handle multiple containers on the same page, you will need to look into ModelFormSet.
0π
I fixed it.
Model code:
class ContainerBox(models.Model):
name = models.CharField(max_length=200)
class CheckBox(models.Model):
name = models.CharField(max_length=60)
containerbox = models.ManyToManyField(
ContainerBox, through="CheckBoxStatus")
class CheckboxStatus(models.Model):
containerbox = models.ForeignKey(ContainerBox, on_delete=models.CASCADE)
checkbox = models.ForeignKey(CheckBox, on_delete=models.CASCADE)
status = models.NullBooleanField()
and template code:
{% for containerbox in object_list %}
<h2>name: {{containerbox.name}}</h2>
{% for checkboxstatus in containerbox.checkboxstatus_set.all %}
{{ checkboxstatus.status}} ({{ checkboxstatus.checkbox }})<br/>
{% endfor %}
{% endfor %}
This does what I need it to do: iterate over containers, then over checkboxes. I just swapped checkboxes and checkboxstatuses.
- Django 1.10 : view function() takes exactly 2 arguments (1 given)
- Django models, How to retrieve a property of a foreign key object
- Django Error while installing graphite