python - 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']
数据是从我的数据库中检索的,我可以从第一个下拉列表中选择一家公司。但是,第二个列表(产品)已锁定。我已将产品与数据库中的公司相关联(使用外键)。
如果你们对我如何解决这个问题有任何想法,那就太好了。我已经搜索了类似的问题,但找不到类似的问题。
这是表格的屏幕截图。
解决方案
我使用了 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 ChainedForeignKey
的models.py
应用程序。
第 5 步:将smart_selects
url 添加到项目的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。
祝一切顺利!
推荐阅读
- css - CSS 动画 - 上下移动的 div 之间的动态曲线
- powerbi - 我可以制作带有 3 轴的 Power BI 趋势图吗?
- http - http请求中有多个get请求
- python - 尝试在while循环中除外 - python
- oracle - 我正在尝试在插入新行后使用触发器更新数据库中多个表中的 2 个字段
- angular - ngx-datatable - 引导主题 - 列标题
- entity-framework - 使用 EntityFramework 时如何限制 INSERT 中使用的列数?
- highcharts - Highcharts 跳过大型数据集的共享工具提示点
- react-native - 如何从 react-native 中的文本区域获取输入字符串
- azure - 如何通过 PowerShell 禁用 Azure 数据仓库的地理备份策略?