0

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?

ikkuh
  • 4,473
  • 3
  • 24
  • 39
  • 'required opt-ins' doesn't sound right. Is that like agreeing to terms? Did you consider moving them out of opt-ins into individual boolean fields? – Ramkishore M Apr 12 '18 at 08:01
  • Yes, it's like agreeing to a term. Each opt-in represents a different term. Staff users on the website need to be able to add a new term (`OptIn`) which should then be included in the form. This means I optins can not be boolean fields to the model. Boolean fields on the form could possible if they are created dynamically. – ikkuh Apr 12 '18 at 08:07
  • Okay. If you add a new required opt-in to an existing Lead, what happens to the records of that Lead created before? – Ramkishore M Apr 12 '18 at 08:42
  • No changes need to be made to old lead records. They haven't seen the new opt-in so they simply don't agree (no relation to the new opt-in). There is also no need to ask them again even though the opt-in is required. – ikkuh Apr 12 '18 at 08:51
  • Okay. I think you could use a third model as a relation between Lead and OptIn rather than ManyToManyField. You can then use formsets for the optins on the Lead form page. The formset items will hold a booleanfield to check as True. Either this or you need to use a custom form with customized validations and error sections. – Ramkishore M Apr 12 '18 at 09:06

0 Answers0