我尝试使用Django-smart-selects
,这应该允许您创建链式forms
。
所以我决定在添加到我的项目之前尝试一个简单的例子。问题是它在Admin
中正常工作,但它在模板中不起作用(使用view方法呈现)。
它不会引发任何错误,但是当我在大陆下拉菜单中选择Country
时,它不会填充Continent
下拉菜单。
请注意,问题不在MODELS.PY中,因为它在管理员中正常工作。
有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})
ADMIN.PY:
...
admin.site.register(Continent)
admin.site.register(Country)
admin.site.register(Location)
...
URLS.PY:
...
url(r'^chaining/', include('smart_selects.urls')),
...
的test.html:
{% extends "base.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
{{ location_form }}
</form>
{% endblock %}
MODELS.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
)
答案 0 :(得分:0)
您必须在test.html中以{{form.media}}或您的案例{{location_form.media}}加载表单媒体,以便包含javascript / css文件。