[Answer]-Django ModelForm: Making an "Other" Textarea manditory when the user selects "Other" from RadioSelect

1๐Ÿ‘

โœ…

You have to define a custom clean method on you model (rather than on your form to make this validation more reusable) :

models.py

from django.core.exceptions import ValidationError

class Person(models.Model):

    PARTY_BENEFIT = (
        ('NO', 'No'),
        ('YES_DEMOCRAT', 'Yes, Democrat'),
        ('YES_REPUBLICAN', 'Yes, Republican'),
        ('YES_OTHER', 'Other')
    )   
    party_benefit = models.CharField(null=True, max_length=100, default=None, choices=PARTY_BENEFIT, verbose_name="Does one or another political party benefit more than the others due to Biased coverage in the media? \n And if so which?")
    party_benefit_message = models.CharField(max_length=1000, blank=True, verbose_name='If you selected \"Other\", please specify:')

    def clean(self):
        if self.party_benefit == 'YES_OTHER' and not self.party_benefit_message:
            raise ValidationError({'party_benefit_message': ['You must enter a message.']})

More info on model validation here : https://docs.djangoproject.com/en/1.8/ref/models/instances/#django.db.models.Model.clean

You form does not change.

๐Ÿ‘คCharlesthk

0๐Ÿ‘

I would write it like this (clean method inside your ModelForm):

def clean(self):
    benefit_option = self.cleaned_data.get('party_benefit')
    message = self.cleaned_data.get('party_benefit_message')
    if benefit_option and benefit_option == 'YES_OTHER' and message is None:
        raise forms.ValidationError('Message is required when \"Other\" is checked')
๐Ÿ‘คbellum

Leave a comment