在Django中向管理员展示多个选项

2 投票
4 回答
10916 浏览
提问于 2025-04-17 14:09

我想给管理员提供多个选项,这样他可以一次性选择多个。我打算用复选框来实现这个功能。但是我尝试后发现,显示的不是复选框,而是一个下拉列表。

这是我的代码。

models.py

class segmentation_Rules(models.Model):
        Segmentation_Rules_CHOICES = (
                        (1, 'At least one order'),
                        (2, 'Have reward points'),
                        )
        Rules       =models.CharField(max_length=100, blank=True,verbose_name="Select rules for customer segmentation",choices=Segmentation_Rules_CHOICES) 

forms.py

class Segmentation_Form(ModelForm):
        Rules = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple)

admin.py

class MyAdmin(admin.ModelAdmin):
    form = Segmentation_Form

所以请告诉我怎么做,才能让管理员从选项中选择多个字段。

编辑:

如果我把选项从模型中去掉,然后在表单中定义它们,管理员看到的就只有一个文本框,没有任何选项可选。

Segmentation_Rules_CHOICES = (
            (1, 'At least one order'),
            (2, 'Have reward points'),
            )

class Segmentation_Form(ModelForm):
        Rules = forms.MultipleChoiceField(choices=Segmentation_Rules_CHOICES, widget=forms.CheckboxSelectMultiple())

        class Meta:
            model=segmentation_Rules

4 个回答

1

在管理后台使用CharField模型的多个选项

它将选项用逗号分隔开来存储。

models.pyadmin.py保持不变

forms.py

from my_project.model import segmentation_Rules 

class Segmentation_Form(ModelForm):
      Rules = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=segmentation_Rules.Segmentation_Rules_CHOICES, required=False)

      def __init__(self, *args, **kwargs):
          super(Segmentation_Form, self).__init__(*args, **kwargs)
          if kwargs.get('instance'):
              self.initial['Rules'] = eval(self.initial['Rules'])
1

我正在使用这个,效果很好。

Rules = forms.MultipleChoiceField(choices=mychoices, widget=forms.CheckboxSelectMultiple)

我觉得在CheckboxSelectMultiple后面不需要加()

2

你需要从models.py文件中的模型字段定义里去掉choices这个参数,然后在forms.py文件里的Rules表单字段里添加choices字段。具体操作如下:

models.py

class segmentation_Rules(models.Model):
    Segmentation_Rules_CHOICES = (
        (1, 'At least one order'),
        (2, 'Have reward points'),
    )
    Rules = models.CharField(max_length=100, blank=True, verbose_name="Select rules for customer segmentation") 

forms.py

class Segmentation_Form(ModelForm):
    Rules = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=models.segmentation_Rules.Segmentation_Rules_CHOICES)

撰写回答