How can I group checkboxes produced by CheckboxSelectMultiple by a related model?
This is best demonstrated by example.
models.py:
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)
forms.py:
class WidgetForm(forms.ModelForm):
features = forms.ModelMultipleChoiceField(
queryset=Feature.objects.all(),
widget=forms.CheckboxSelectMultiple,
required=False
)
class Meta:
model = Widget
views.py:
def edit_widget(request):
form = WidgetForm()
return render(request, 'template.html', {'form': form})
template.html:
{{ form.as_p }}
The above produces the following output:
[] Widget 1
[] Widget 2
[] Widget 3
[] Widget 1
[] Widget 2
What I would like is for the feature checkboxes to be grouped by feature category (based on the ForeignKey):
Category 1:
[] Widget 1
[] Widget 2
[] Widget 3
Category 2:
[] Widget 1
[] Widget 2
How can I achieve this? I have tried using the {% regroup %} template tag to no avail.
Any advice much appreciated.
Thanks.
You have to write the custom
CheckboxSelectMultiplewidget. Using the snippet I have tried make theCheckboxSelectMultiplefield iterable by adding thecategory_nameas an attribute in fieldattrs. So that I can useregrouptag in template later on.The below code is modified from snippet according to your need, obviously this code can be made more cleaner and more generic, but at this moment its not generic.
forms.pyThen in template:
Results:
I added countries name in category table, and cities name in features table so in template I was able to regroup the cities (features) according to country (category)