【发布时间】:2016-04-14 18:20:10
【问题描述】:
我正在尝试使用Django-smart-selects,它应该允许您创建链式forms。
所以我决定在添加到我的项目之前先尝试一个简单的示例。问题是它在Admin 中正常工作,但在模板中不起作用(使用视图方法渲染)。
它不会引发任何错误,但当我在大陆下拉菜单中选择Continent 时,它不会填充Country 下拉菜单。
请注意,问题可能不在 MODELS.PY 中,因为它在 Admin 中可以正常工作。
有3个地点:
- 美国 - 纽约
- 美国 - 德克萨斯
- 非洲 - 摩洛哥
有两种形式 - 大陆和国家。如果我没有选择Continent,我将无法选择任何国家。如果我选择 America,则第二个菜单将填充 NewYork 和 Texas,这是正确的。这是在管理员。在模板中,我可以选择大陆
代码如下:
FORMS.PY:
class LocationForm(forms.ModelForm):
class Meta:
model = Location
fields = ('newcontinent','newcountry',)
VIEWS.PY:
def test(request):
location_form = LocationForm()
if request.method=='POST':
print request.cleaned_data
return render(request,'test.html', context={'location_form':location_form})
管理员.PY:
...
admin.site.register(Continent)
admin.site.register(Country)
admin.site.register(Location)
...
URLS.PY:
...
url(r'^chaining/', include('smart_selects.urls')),
...
测试.HTML:
{% extends "base.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
{{ location_form }}
</form>
{% endblock %}
模型.PY:
class Continent(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length=40)
continent = models.ForeignKey(Continent)
def __str__(self):
return self.name
from smart_selects.db_fields import ChainedForeignKey
class Location(models.Model):
newcontinent = models.ForeignKey(Continent)
newcountry = ChainedForeignKey(
Country, # the model where you're populating your countries from
chained_field="newcontinent", # the field on your own model that this field links to
chained_model_field="continent", # the field on Country that corresponds to newcontinent
show_all=True, # only shows the countries that correspond to the selected continent in newcontinent
)
【问题讨论】:
标签: python django django-models django-forms django-smart-selects