[Django]-ChoiceField or CharField in django form

5👍

The best approach is to have just a CharField in your models/forms with a custom widget to display your choices and ‘other’ with the right behavior.

👤rz.

2👍

RZ has a good solution

An alternative solution (with less javascript) is to have a hidden “other” CharField that is made visible when the “Other” option is selected on your ChoiceField

edit: Hidden as in style="display: none;" not a HiddenInput field

something like (with jQuery):

$("#id_myChoiceField").change(function() {
    if ($(this).val() == 'other') {
        $("#id_myOtherInput").show();
    }
    else {
        $("#id_myOtherInput").hide();
    }
});

You’ll have to write your own validation code though and set required=False on the “Other” Charfield

👤Jiaaro

0👍

Your class for that form should look something like this:

class ChoicesForm(forms.ModelForm):
    # some other fields here
    ...
    other = forms.CharField(required=False)
    ...

Just create a javascript that displays the ‘other’ text input if the user chooses ‘other’ among the choices.

Leave a comment