title: Grouped CheckboxSelectMultiple in Django template
body: <p>How can I group checkboxes produced by <code>CheckboxSelectMultiple</code> by a related model?</p>
  
  <p>This is best demonstrated by example.</p>
  
  <p><strong>models.py:</strong></p>
  
  <pre><code>class FeatureCategory(models.Model):
      name = models.CharField(max_length=30)
  
  class Feature(models.Model):
      name = models.CharField(max_length=30)
      category = models.ForeignKey(FeatureCategory)
  
  class Widget(models.Model):
      name = models.CharField(max_length=30)
      features = models.ManyToManyField(Feature, blank=True)
  </code></pre>
  
  <p><strong>forms.py:</strong></p>
  
  <pre><code>class WidgetForm(forms.ModelForm):
      features = forms.ModelMultipleChoiceField(
          queryset=Feature.objects.all(),
          widget=forms.CheckboxSelectMultiple,
          required=False
      )
      class Meta:
          model = Widget
  </code></pre>
  
  <p><strong>views.py:</strong></p>
  
  <pre><code>def edit_widget(request):
      form = WidgetForm()
      return render(request, 'template.html', {'form': form})
  </code></pre>
  
  <p><strong>template.html:</strong></p>
  
  <pre><code>{{ form.as_p }}
  </code></pre>
  
  <p>The above produces the following output:</p>
  
  <pre><code>[] Widget 1
  [] Widget 2
  [] Widget 3
  [] Widget 1
  [] Widget 2
  </code></pre>
  
  <p>What I would like is for the feature checkboxes to be grouped by feature category (based on the <code>ForeignKey</code>):</p>
  
  <pre><code>Category 1:
    [] Widget 1
    [] Widget 2
    [] Widget 3
  
  Category 2:
    [] Widget 1
    [] Widget 2
  </code></pre>
  
  <p>How can I achieve this? I have tried using the <code>{% regroup %}</code> template tag to no avail.</p>
  
  <p>Any advice much appreciated.</p>
  
  <p>Thanks.</p>