For each possible many to many relation I want a form to have separate checkboxes. I know this is possible using the CheckboxSelectMultiple
, but it seems I can't have individual error messages per checkbox.
# models.py
class OptIn(models.Model):
required = models.BooleanField(default=False)
description = models.TextField()
def __str__(self):
return self.description
class Lead(models.Model):
optins = models.ManyToManyField(OptIn, blank=True)
# forms.py
class LeadForm(forms.ModelForm):
class Meta:
model = Lead
fields = ['optins']
widgets = {
'optins': forms.CheckboxSelectMultiple
}
def clean_optins(self):
# Errors raised here are for the entire field
I want people signing up on the website (Lead
) being able to agree to a number of opt-ins (OptIn
). Opt-ins can be optional or required for the user. For the required opt-ins I want to show an error message or add a class when the user doesn't agree to them. Raising errors in clean_optins
shows the error for the entire optins field.
Can a custom template for the CheckboxSelectMultiple
widget handle this in a nice way or is there a better way to implement this functionality?