跳转至

Django-multiselectfield实现固定值多选

安装

pip install django-multiselectfield

model

from multiselectfield import MultiSelectField

MultiCategory = (
    (0, '测试1'),
    (1, '测试2'),
    (2, '测试3'),
    (3, '测试4'),
)

# 用药对账
class Demo(models.Model):
    # 类型
    categories = MultiSelectField(choices=MultiCategory,
                                  max_length=255,
                                  verbose_name='类型')
    ...

自定义模板

It is possible to customize the HTML of this widget in your form template. To do so, you will need to loop throughform.{field}.field.choices. Here is an example that displays the field label underneath/after the checkbox for aMultiSelectField called providers:

{% for value, text in form.providers.field.choices %}
  <div class="ui slider checkbox">
    <input id="id_providers_{{ forloop.counter0 }}" name="{{ form.providers.name }}" type="checkbox" value="{{ value }}"{% if value in checked_providers %} checked="checked"{% endif %}>
    <label>{{ text }}</label>
  </div>
{% endfor %}

未测试,直接引用文档。前端可配合库multi-select使用。

Django REST Framework

from rest_framework import fields

# 新建 categories参数传递list
class DemoCreateSerializer(ModelSerializer):
    categories = fields.MultipleChoiceField(choices=MultiCategory, label='类型')
    ...
# 列表 详情
class DemoSerializer(ModelSerializer):
    class Meta:
        model = Demo
        fields = ('id', 'category', 'get_category_display')

列表和详情大致会返回如下格式的数据:

{
    "id": 7,
    "categories": [
        "0",
        "1",
        "2"
    ],
    "get_categories_display": "测试1, 测试2, 测试3"
}

选项值为Int类型时,报错TypeError: sequence item int_value: expected str instance, int found

据原作者所说,这个问题为了兼容性不方便修改。 自行在代码里做了兼容,

from multiselectfield import MultiSelectField


class MultiSelectCompatIntField(MultiSelectField):
    def get_prep_value(self, value):
        return '' if value is None else ','.join([str(x) for x in value])

使用MultiSelectCompatIntField替换MultiSelectField即可,将value里的itemint转为str

Pull Request #86