0

我正在嘗試使用Django-smart-selects,它應該允許您創建鏈接forms窗體在管理中正常工作,但不在模板中

所以我決定嘗試一個簡單的例子,然後再添加到我的項目中。問題是它在Admin中正常工作,但它在模板中不起作用(使用視圖方法呈現)。

它不會引發任何錯誤,但當我在continent下拉菜單中選擇Continent時,它不會填充Country下拉菜單。

請注意,問題不大可能在MODELS.PY中,因爲它在Admin中正常工作。

有3個位置:

  1. 美國 - 紐約
  2. 美國 - 得克薩斯
  3. 非洲 - 摩洛哥

有兩種形式 - 大陸和國家。如果我沒有選擇Continent,我無法選擇任何國家。如果我選擇美國,那麼第二個菜單就是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

必須在您的test.html加載形式媒體{{form.media}}或你的情況{{location_form.media}}以包含javascript/css文件。

相關問題