Will M.
Will M.

Reputation:

ChoiceField or CharField in django form

I have a CharField in the model that needs to be selected by a ChoiceField. If the user's choice is not in the choice field then they'd select "other" and be able to type in a text input. How can I do this? I don't need the javascript; just the help with the django part.

Upvotes: 3

Views: 3510

Answers (3)

Amazing Angelo
Amazing Angelo

Reputation: 1728

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.

Upvotes: 0

Jiaaro
Jiaaro

Reputation: 76918

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

Upvotes: 2

rz.
rz.

Reputation: 20037

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.

Upvotes: 5

Related Questions