1

I'm using Django 1.9.1. I have a form that has Categories like this:

class MyModelEditForm(forms.ModelForm):

    class Meta:

        model = MyModel
        fields = ['name',
                  'email',
                  'categories',
                  ]

        widgets = {
            'categories': forms.CheckboxSelectMultiple(),
        }

Here's the Models:

class MyModel(models.Model):

    name = models.CharField(max_length=256, verbose_name='navn')
    email = models.EmailField(null=True, blank=True)
    categories = models.ManyToManyField(Category)

class Category(models.Model):
    name = models.CharField(max_length=128)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

When I use my form in a template I can say {{ form.categories }} and I get a bunch of checkboxes with all my categories! Excellent, functionally this is exactly what I want. And like this, everything works. My problem is that I don't want the input fields nested in labels, as Django defaults to. So I tried to loop over the categories like this:

      {% for category in form.categories %}
            <input type="checkbox" name="{{ category.name }}" class="styled-checkbox" value="{{ category.id }}" id="{{ category.id_for_label }}" {% if category.is_checked %}checked="checked"{% endif %}>
            <label for="{{ category.id_for_label }}">{{ category.choice_label }}</label>
      {% endfor %}

But apparently I can't set the value to {{ category.id }}, it renders nothing. I also tried {{ category.related__id }} but that's not a thing either. Looked in the documentation, but it doesn't really seem to say allot about this issue. If there's a way to only output the input tag and that would be acceptable as well.

So is it even possible to access the related objects id from here? Or is there another way to customise the output? I looked at overriding the render() method, but it seemed like a huge effort just to move the input outside of a label tag.

Jonas Lomholdt
  • 1,215
  • 14
  • 23
  • What do you mean by ` I don't want the input fields nested in labels, as Django defaults to.`? As far as I know django outputs the HTML similar to what you are doing i.e. input and label tags as siblings. – Muhammad Tahir Apr 15 '16 at 18:35
  • I'm actually not sure if it's only CheckboxSelectMultiple, but the output is `` with the input field nested within the label. – Jonas Lomholdt Apr 15 '16 at 18:38
  • You can find help here http://stackoverflow.com/questions/9221010/how-do-i-iterate-over-the-options-of-a-selectfield-in-a-template. It is not exact duplicate so I am not voting for duplicate. But it is very very close to what you need. – Muhammad Tahir Apr 15 '16 at 18:46
  • Can't seem to make that work. Using `form.fields.customer.queryset` will give me the id, but then I seem to loose the ability to use is_checked and more. – Jonas Lomholdt Apr 15 '16 at 19:48

0 Answers0