Django - 如何使用 'Other' 文本输入字段创建包含复选框的表单字段

Django - how to create a form field containing checkboxes WITH an 'Other' text input field

我正在 Django 中创建一个表单,并希望为用户提供一个复选框列表,其中可以选择将其他 _____ 文本输入作为其中一个选项。这是我使用 MultipleChoiceFieldCheckboxSelectMultiple 的代码:

class IntakeFormSimple(Form):
    def __init__(self, *args, **kwargs):
        super(IntakeFormSimple, self).__init__(*args, **kwargs)

    preferred_pronouns = forms.MultipleChoiceField(
        choices=(("she/her", "she/her"), ("he/him", "he/him"), ("they/them", "they/them")),  # <--- add "Other" here
        label="What are your preferred pronoun(s)?",
        widget=forms.CheckboxSelectMultiple,
    )

您需要使用 CharFieldTextField 而不是 MultipleChoiceField。然后您需要创建一个自定义小部件,它是 MultipleSelectTextInput 小部件的组合。我建议使用 MultiWidget 将这两个小部件添加在一起 ​​(https://docs.djangoproject.com/en/4.0/ref/forms/widgets/#multiwidget) 并添加纯粹装饰性的“其他”复选框,它使用一些 JS 来 enable/disable 文本输入。为此,您需要使用自定义小部件模板。

我怀疑您还需要覆盖字段 class 才能使其与您的自定义小部件一起使用。

希望我为您指明了正确的方向。

将“其他”字段添加到您的表单中:

class IntakeFormSimple(Form):
def __init__(self, *args, **kwargs):
    super(IntakeFormSimple, self).__init__(*args, **kwargs)

preferred_pronouns = forms.MultipleChoiceField(
    choices=(("she/her", "she/her"), ("he/him", "he/him"), ("they/them", "they/them", "other")), 
    label="What are your preferred pronoun(s)?",
    widget=forms.CheckboxSelectMultiple,
)

现在在您的 javascript 文件中,在页面加载时隐藏该输入:

$("#user-input-textbox").hide();

最后,使用'other'单选按钮被选中并在未选中时将其隐藏,并在隐藏前清除现有值:

    $('#Other').click(function(){
        if ($(this).is(':checked')){
            $("#user-input-textbox").show();
        }
        else{
             $("#user-input-textbox").html('');
             $("#user-input-textbox").hide();
        }
    });