Python 表单在管理中正常工作,但在模板中无法正常工作
我正在尝试使用Python 表单在管理中正常工作,但在模板中无法正常工作,python,django,django-models,django-forms,django-smart-selects,Python,Django,Django Models,Django Forms,Django Smart Selects,我正在尝试使用Django智能选择,它应该允许您创建链接的表单 因此,在添加到我的项目之前,我决定在一个简单的示例上尝试它。问题是它在Admin中正常工作,但在模板中不工作(使用视图方法呈现) 它不会引发任何错误,但在大陆下拉菜单中选择大陆时,它不会填充国家下拉菜单 请注意,问题可能不在MODELS.PY中,因为它在Admin中正常工作 有3个地点: 美国-纽约 美国-德克萨斯州 非洲-摩洛哥 有两种形式——大陆和国家。如果我没有选择大陆,我就不能选择任何国家。如果我选择美国,第二个菜单上有纽约
Django智能选择
,它应该允许您创建链接的表单
因此,在添加到我的项目之前,我决定在一个简单的示例上尝试它。问题是它在Admin
中正常工作,但在模板中不工作(使用视图方法呈现)
它不会引发任何错误,但在大陆下拉菜单中选择大陆
时,它不会填充国家
下拉菜单
请注意,问题可能不在MODELS.PY中,因为它在Admin中正常工作
有3个地点:
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)
...
URL.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 %}
您必须将test.html中的表单媒体加载为{{form.media}}或案例{location\u form.media},以便包含javascript/css文件
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
)