表单在Admin中正常工作,但在Template中无效



我正在尝试使用Django-smart-selects,它应该允许您创建链接的forms

所以我决定在添加到我的项目之前,先在一个简单的例子上尝试一下。问题是它在Admin中正常工作,但在模板(使用视图方法渲染)中不工作。

它不会引发任何错误,但当我在大陆下拉菜单中选择Continent时,它不会填充Country下拉菜单。

请注意,问题可能不在型号中。PY,因为它在Admin中工作正常。

有3个位置:

  1. 美国-纽约
  2. 美国-德克萨斯州
  3. 非洲-摩洛哥

有两种形式——大陆和国家。如果我没有选择Continent,我就无法选择任何国家。如果我选择美国,第二个菜单上有纽约和德克萨斯,这是正确的。这是在管理中。在模板中,我可以选择Continent

这是代码:

表格。PY:

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        fields = ('newcontinent','newcountry',)

视图。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)
...

url。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
    )

您必须将test.html中的表单媒体加载为{{form.media}}或您的情况下的{{location_form.media}},以便包含javascript/css文件。

最新更新