开发者

ChoiceField or CharField in django form

开发者 https://www.devze.com 2022-12-23 17:50 出处:网络
I have a CharField in the model that needs to be sel开发者_如何学运维ected 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 tex

I have a CharField in the model that needs to be sel开发者_如何学运维ected 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.


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 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消