Django-smart-selects
を使用しようとしていますが、これはチェーンforms
を作成できるようにする必要があります。フォームは正しく管理者で動作しますが、テンプレートにはありません
私はプロジェクトに追加する前に簡単な例で試してみることにしました。問題は、それがAdmin
で正しく動作するが、(ビューメソッドを使用してレンダリングされた)テンプレートでは機能しないということです。
大陸のドロップダウンメニューでContinent
を選択すると、エラーは発生しませんが、Country
ドロップダウンメニューには入りません。
この問題は、おそらくMODELS.PYではなく、Adminで正しく機能するためです。
- アメリカ -
- アメリカニューヨーク アメリカ - テキサス
- アフリカ - モロッコ
二つの形式があります - 大陸と国:
は3つの場所があります。 Continent
を選択していない場合は、国を選択できません。アメリカを選択すると、2番目のメニューに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
)