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.