Cop*_*opp 2 python django django-models 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)])
Run Code Online (Sandbox Code Playgroud)
然后我定义了一个表单:
表格.py
class Rates(forms.ModelForm):
class Meta:
model = Rates
fields= ['company', 'product', 'taux_comm_1', 'taux_comm_2']
Run Code Online (Sandbox Code Playgroud)
数据是从我的数据库中检索的,我可以从第一个下拉列表中选择一家公司。但是,第二个列表(产品)已锁定。我已将产品与数据库中的公司相关联(使用外键)。
如果你们对我如何解决这个问题有任何想法,那就太好了。我搜索了类似的问题,但找不到类似的问题。
这是表格的屏幕截图。
我使用了 JS Lint 分支(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`
Run Code Online (Sandbox Code Playgroud)
第3步:添加'smart_selects',到INSTALLED_APPS列表中settings.py。
第4步:添加from smart_selects.db_fields import ChainedForeignKey在models.py你的应用程序中。
第 5 步:将smart_selectsurl添加到项目的urls.py. 这是Chained Selects和Chained ManyToMany选择所必需的。例如:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^chaining/', include('smart_selects.urls')),
)
Run Code Online (Sandbox Code Playgroud)
第 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。
祝一切顺利!