ChoiceField or CharField in django form

I have a CharField in the model to be selected by ChoiceField. If the user's selection is not in the selection field, they select "other" and can enter text input. How can i do this? I do not need javascript; just help with a piece of django.

+3
source share
3 answers

The best approach is to have only CharField in your models / forms with custom widgets to display your options and "others" with the right behavior.

+5
source

RZ has a good solution

( javascript) , "" CharField, , "" ChoiceField

edit: , style="display: none;" HiddenInput

- ( jQuery):

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

required=False "Other" Charfield

+2

Your class for this form should look something like this:

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

Just create javascript that will display “different” text input if the user selects “other” among the options.

0
source

Source: https://habr.com/ru/post/1737700/


All Articles