[Answered ]-Django dynamic variable form fields


The short answer is that this requires a mixture of CSS, javascript and django forms.

The Form

Step 1 is create a form with conditional validation se my clean method.

from django import forms
from django.utils.translation import ugettext as _
from django.forms.widgets import RadioSelect, Textarea, CheckboxSelectMultiple
from django.utils.safestring import mark_safe

class FormContact(forms.Form):
    The contact form
    choice_a = forms.ChoiceField(
        label=_(u' '),
            (1, mark_safe(_(u'First Option'))),
            (0, mark_safe(_(u'Second Option'))),
    show_if_choice_1 = forms.CharField(
        label=_(u'Choice 1 text box')
    show_if_choice_2 = forms.CharField(
        label=_(u'Choice 2 text box')

    def clean(self):
        super(forms.Form, self).clean()

        if 'choice_a' in self.cleaned_data :
            if self.cleaned_data['choice_a'] == '1':
                if self.cleaned_data['show_if_choice_1'] == '' :
                    self._errors['show_if_choice_1'] = self.error_class([_(u'Please Fill out choice 1 text box.'),])
            if self.cleaned_data['choice_a'] == '2':
                if self.cleaned_data['show_if_choice_2'] == '' :
                    self._errors['show_if_choice_2'] = self.error_class([_(u'Please fill out choice 2 box'),])

        return self.cleaned_data

The JS and CSS

write some javascript + CSS to show hide fields based on the value of the conditional field.

Note: If you need more direction please just tell me, I didn’t want to spend an eternity typing if you got the jist quickly.

Leave a comment