django admin复选MultiSelectField的使用

参考文档:https://pypi.org/project/django-multiselectfield/

1,先安装

pip install django-multiselectfield

2,修改settings.py

INSTALLED_APPS = [
    'simpleui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'import_export',
    'multiselectfield',
]

3,实例参考方法:

from multiselectfield import MultiSelectField

# ...

MY_CHOICES = (('item_key1', 'Item title 1.1'),
              ('item_key2', 'Item title 1.2'),
              ('item_key3', 'Item title 1.3'),
              ('item_key4', 'Item title 1.4'),
              ('item_key5', 'Item title 1.5'))

MY_CHOICES2 = ((1, 'Item title 2.1'),
               (2, 'Item title 2.2'),
               (3, 'Item title 2.3'),
               (4, 'Item title 2.4'),
               (5, 'Item title 2.5'))

class MyModel(models.Model):

    # .....

    my_field = MultiSelectField(choices=MY_CHOICES)
    my_field2 = MultiSelectField(choices=MY_CHOICES2,
                                 max_choices=3,
                                 max_length=3)

4,当你想使用form直接在前端生成编辑或查看数据库内容的页面时,MultiSelectField的项不能直接显示出来,而是需要进行特殊的处理,其格式如下(其中provider表示query对象,field表示MultiSelectField项)

{% for value, text in 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 %}

 

posted @ 2023-03-29 09:12  super_ip  阅读(202)  评论(0编辑  收藏  举报