【问题标题】:Formatting multiple BooleanFields as a single Select widget将多个 BooleanField 格式化为单个 Select 小部件
【发布时间】:2021-04-29 21:30:34
【问题描述】:

我正在使用的数据库有几个布尔字段,一次只有一个应该为真。 我想将它们格式化为 Select 小部件,以便我可以将每个布尔字段列为选项,并且将为除所选选项之外的所有布尔字段返回 False。

我将它们中的每一个单独用作复选框(我已将它们注释掉),并且我能够制作一个在视图中正确显示的选择小部件 (client_type),但我无法完成上述操作。

这是我的 models.py 的相关部分:

class DomCase(models.Model):
    plaintiff = models.BooleanField(default=False, blank=True)
    defendant = models.BooleanField(default=False, blank=True)

class DomCaseForm(ModelForm):
    client_type = ChoiceField(choices=(('', '----'),('plaintiff', 'Plaintiff'),('defendant','Defendant')), widget=Select(attrs={'class': 'form-control', 'id': 'client_type'}))

    class Meta:
        model = DomCase

        widgets = {
            #'plaintiff': CheckboxInput(attrs={'class': 'custom-control-input', }),
            #'defendant': CheckboxInput(attrs={'class': 'custom-control-input', }),
        }

        # Dynamically Create Form Fields based on widget details
        fields = []
        for widget in widgets:
            fields.append(widget)
        fields = tuple(fields)

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    我想我解决了我的问题!

    我最终将那些工作的复选框重新添加回并用display: none; 隐藏它们,然后我使用 jQuery 根据选择框的值动态取消选中并选中这些框。

    我将复选框小部件更改为以下内容:

            widgets = {
                'plaintiff': CheckboxInput(attrs={'style': 'display: none;'}),
                'defendant': CheckboxInput(attrs={'style': 'display: none;'}),
            }
    

    并在我的模板中添加了以下 jQuery 来处理交互:

        $('#client_type').change(function() {
            if ($('#client_type').val() == "defendant") {
                $('#id_defendant').prop("checked", true);
                $('#id_plaintiff').prop("checked", false);
            }
            else if ($('#client_type').val() == "plaintiff") {
                $('#id_defendant').prop("checked", false);
                $('#id_plaintiff').prop("checked", true);
            } else {
                $('#id_defendant').prop("checked", false);
                $('#id_plaintiff').prop("checked", false);
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2017-10-02
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多