首页 > 解决方案 > Django 中的链式选择 [模块:django-smart-selects]

问题描述

我正在尝试使用 django-smart-selects 模块来创建相关的下拉列表。我已经按照文档和定义的模型使用了“ChainedForeignKey”来定义我的公司和我的产品之间的链接。

模型.py

class Company(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name


class Product(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Rates(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    product = ChainedForeignKey(
        Product,
        chained_field = "company",
        chained_model_field = "company",
        show_all = False,
        auto_choose = True,
        sort=True)
     taux_comm_1 = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(1)])
     taux_comm_2 = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(1)]) 

然后我定义了一个表格:

表格.py

class Rates(forms.ModelForm):
    class Meta:
        model = Rates
        fields= ['company', 'product', 'taux_comm_1', 'taux_comm_2']

数据是从我的数据库中检索的,我可以从第一个下拉列表中选择一家公司。但是,第二个列表(产品)已锁定。我已将产品与数据库中的公司相关联(使用外键)。

如果你们对我如何解决这个问题有任何想法,那就太好了。我已经搜索了类似的问题,但找不到类似的问题。

这是表格的屏幕截图。

这是表格的截图

标签: pythondjangodjango-modelsdjango-smart-selects

解决方案


我使用了 JS Lint brach ( https://github.com/digi604/django-smart-selects/tree/js-unlinting-fixes ),它解决了这个问题。

参考:https ://github.com/digi604/django-smart-selects/issues/258

编辑:添加分步说明来解决问题:

第 1 步:删除现有版本的 django-smart-selects。输入pip uninstall django-smart-selects终端。

第 2 步:通过键入安装 JS-lint 分支

pip install git+https://github.com/digi604/django-smart-selects.git@js-unlinting-fixes` 

第三步:添加'smart_selects',INSTALLED_APPS列表中settings.py

第 4 步:添加您from smart_selects.db_fields import ChainedForeignKeymodels.py应用程序。

第 5 步:smart_selectsurl 添加到项目的urls.py. Chained Selects这对于andChained ManyToMany选择是必需的。例如:

urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^chaining/', include('smart_selects.urls')),
)

第 6 步:您还需要在每个包含smart_selects. 添加USE_DJANGO_JQUERY = True项目的settings.py.

第 7 步:在 HTML 文件中添加{{ form.media.js }}之前{{ form.as_table }},以便从 Django 模型派生的 Django 表单反映智能选择功能。

我正在使用 Python 2.7.10 和 Django 1.11。

祝一切顺利!


推荐阅读