[Fixed]-How to correctly use template tags in this specific Many-to-Many relationship in Django?

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.

πŸ‘€Rob Vezina

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.

πŸ‘€Robin Papa

Leave a comment