Question

I'm new to both django and python and currently trying to build a form with various options as well as an "other" option for options not on the list. I'd like to define the option such that when "other" is checked, the form only validates if the other text box contains a non-empty value.

Is there a proper way to extend django forms/fields/widgets to accomplish this? The closest thing could find after searching google and stackoverflow is this example which provides code to extend create a custom renderer, widget, and form field but it is based on an older version of django.

Was it helpful?

Solution

If you're using django.forms.ModelForm to render your forms you can do this in the form validation for your options field (clean_[your field name]).

from django import forms

class YourModelForm(forms.ModelForm):
    def clean_your_options(self):
        your_options = self.cleaned_data.getlist('your_options')

        if 'other' in your_options:
            other_text_input = self.cleaned_data.get('other_text_input')
            if len(other_text_input) == 0:
                raise forms.ValidationError('Other text input must contain value')

        return your_options
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top