我正在尝试使用Django-smart-selects,它应该允许您创建链接的forms。
所以,我决定在添加到我的项目之前,先在一个简单的例子上尝试一下。问题是它在Admin中正确工作,但在模板中不工作(使用视图方法呈现)。
它不会引发任何错误,但当我在“大陆下拉菜单”中选择“Country”下拉菜单时,它不会填充Continent下拉菜单。
请注意,这个问题可能不在MODELS.PY中,因为它在Admin中正常工作。
有3个地点:
有两种形式--欧洲大陆和国家。如果我没有选择Continent,我就不能选择任何国家。如果我选择美国,第二个菜单是填充NewYork和德州,这是正确的。这是在行政部。在模板中,我可以选择欧洲大陆
以下是代码:
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
)发布于 2016-04-15 10:22:17
必须将test.html中的表单媒体加载为{{ form.media }}或为您的情况加载{ location_form.media },以便包含javascript/css文件。
https://stackoverflow.com/questions/36630979
复制相似问题