跳转到主要内容

使用Select2 jQuery插件的Django表单字段

项目描述

https://travis-ci.org/theatlantic/django-select2-forms.svg?branch=master

django-select2-forms 是一个项目,它提供了使用 Select2 JavaScript 插件 的 Django 表单字段。该项目由 The Atlantic 的开发者创建。

支持

由于 Django 在 2.0 中增加了对 select2 的支持,因此我们将支持到该版本以保持兼容性。

  • ~=v3.0: Python >=3.7 <3.9 | Django 2.2, 3.1, 3.2(当前版本)

本地开发与测试

以下步骤在您第一次开始时只需执行一次

安装 pyenv

这些说明假设您已经安装了 Homebrew,但没有安装 pyenv

brew install pyenv
touch ~/.bash_profile

将以下行添加到您的 ~/bash_profile.zshrc

eval "$(pyenv init -)"

重新加载您的 shell

. ~/.bash_profile

或者

. ~/.zshrc

Python 仓库设置

首先,克隆仓库并准备您的 Python 环境

git clone https://github.com/theatlantic/django-select2-forms.git
pyenv install 3.7.2
pyenv install 3.8.0
pyenv install 3.9.0
pyenv local 3.7.2 3.8.0 3.9.0
python -V

前一个命令的输出应该是 Python 3.7.2

最后

python -m venv venv

激活您的环境

从基本目录

deactivate  # ignore: -bash: deactivate: command not found
. venv/bin/activate
pip install -U tox

运行测试

如果您尚未这样做,请通过 chromedriver 设置您的环境

brew install --cask chromedriver

运行所有测试

tox -- --selenosis-driver=chrome-headless

显示所有可用的 tox 命令

tox -av

只运行特定的环境

tox -e <environment-name> -- --selenosis-driver=chrome-headless  # example: tox -e py37-django22

只运行特定的测试

tox -- pytest -k test_something --selenosis-driver=chrome-headless

在特定环境中运行任意命令

tox -e py37-django22 -- python  # runs the Python REPL in that environment

设置开发环境

tox -e <pyXX-DjangoYY> --develop -r
. .tox/<pyXX-DjangoYY>/bin/activate

安装

建议使用 pip 进行安装

pip install django-select2-forms

或者,从源代码使用 pip 进行安装

pip install -e git+git://github.com/theatlantic/django-select2-forms.git#egg=django-select2-forms

如果源代码已经检出,请使用 setuptools

python setup.py develop

配置

django-select2-forms 使用 django.contrib.staticfiles 提供静态资源,因此需要在设置的 INSTALLED_APPS 中添加 "select2"

INSTALLED_APPS = (
    # ...
    'select2',
)

要使用 django-select2-forms 的 AJAX 支持,必须在 urls.py 的 urlpatterns 中包含 'select2.urls'

urlpatterns = patterns('',
    # ...
    url(r'^select2/', include('select2.urls')),
)

使用方法

使用 django-select2-forms 的最简单方法是使用 select2.fields.ForeignKeyselect2.fields.ManyToManyField 分别替代 django.db.models.ForeignKeydjango.db.models.ManyToManyField。这些字段扩展了它们的 django 相等字段,并接受相同的参数,以及额外的可选关键字参数。

select2.fields.ForeignKey 示例

在以下两个示例中,一个“条目”只与一个作者相关联。下面的示例不使用 AJAX,而是使用客户端的 autocomplete 过滤功能,通过 html <select> 中的 <option> 元素(标签来自 Author.__str__())。

@python_2_unicode_compatible
class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Entry(models.Model):
    author = select2.fields.ForeignKey(Author,
        overlay="Choose an author...",
        on_delete=models.CASCADE)

此更高级的示例通过 AJAX 使用 Author.name 字段自动完成,并将自动完成搜索限制为 Author.objects.filter(active=True)

class Author(models.Model):
    name = models.CharField(max_length=100)
    active = models.BooleanField()

class Entry(models.Model):
    author = select2.fields.ForeignKey(Author,
        limit_choices_to=models.Q(active=True),
        ajax=True,
        search_field='name',
        overlay="Choose an author...",
        js_options={
            'quiet_millis': 200,
        },
        on_delete=models.CASCADE)

select2.fields.ManyToManyField 示例

在以下基本示例中,条目可以有多个作者。此示例不通过 AJAX 进行作者名称查找,而是使用 Author.__unicode__() 为标签填充 <option> 元素。

@python_2_unicode_compatible
class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Entry(models.Model):
    authors = select2.fields.ManyToManyField(Author)

以下“厨房水槽”示例允许对作者进行排序,并使用 AJAX 在作者名称的两个变体上自动完成。

from django.db import models
from django.db.models import Q
import select2.fields
import select2.models

class Author(models.Model):
    name = models.CharField(max_length=100)
    alt_name = models.CharField(max_length=100, blank=True, null=True)

class Entry(models.Model):
    categories = select2.fields.ManyToManyField(Author,
        through='EntryAuthors',
        ajax=True,
        search_field=lambda q: Q(name__icontains=q) | Q(alt_name__icontains=q),
        sort_field='position',
        js_options={'quiet_millis': 200})

表单字段示例

如果您不需要使用 django-select2-forms 的ajax功能,您可以在不修改模型的情况下在Django表单中使用select2。select2表单字段存在于 select2.fields 模块中,并且与它们的标准Django对应类具有相同的名称(ChoiceFieldMultipleChoiceFieldModelChoiceFieldModelMultipleChoiceField)。上面的第一个 ForeignKey 示例,是用django表单字段完成的。

class AuthorManager(models.Manager):
    def as_choices(self):
        for author in self.all():
            yield (author.pk, force_text(author))

@python_2_unicode_compatible
class Author(models.Model):
    name = models.CharField(max_length=100)
    objects = AuthorManager()

    def __str__(self):
        return self.name

class Entry(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

class EntryForm(forms.ModelForm):
    author = select2.fields.ChoiceField(
        choices=Author.objects.as_choices(),
        overlay="Choose an author...")

    class Meta:
        model = Entry

许可

Django代码采用 简化版BSD许可证,版权属于The Atlantic Media Company。请在根目录下的 LICENSE 文件中查看完整的许可证和版权信息。

包含的Select2 JavaScript库采用 Apache软件基金会许可证版本2.0。请在 select2/static/select2/select2/LICENSE 文件中查看关于Select2 JavaScript库的完整许可证和版权信息。

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定要选择哪个,请了解更多关于 安装包 的信息。

源分布

django-select2-forms-3.0.0.tar.gz (208.6 kB 查看散列)

上传日期

构建分布

django_select2_forms-3.0.0-py3-none-any.whl (216.7 kB 查看散列)

上传日期 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面