私は初めてdjangoをやっています。私は1つの問題を抱えています。私は、www.example.com/{state}/{county}
のような階層的なURLを持つ一連のページを作成しようとしています。基本的に私が持っている問題は、私がwww.example.com/{state}
を得ることができるということですが、私は州/州のページに州を運ぶために、djangoのURLシステムをどのように使うのか分かりません。私が取得し終わると、このファイルには、私はちょうど1の例を紹介します大きいwww.example.com//{county}
Djangoで階層的なURLを作成する
urls.py
app_name = 'main'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<pk>[A-Z]{2})/$', views.StateView.as_view(), name='state'),
url(r'/(?P<pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county'),
]
views.py
def index(request):
return render(request, 'main/index.html', {})
class StateView(generic.ListView):
template_name = 'main/state.html'
context_object_name = 'county_list'
def get_queryset(self):
counties = [ // list of a couple counties for testing purposes]
return counties
class CountyView(generic.ListView):
template_name = 'main/county.html'
context_object_name = 'water_list'
def get_queryset(self):
return WaWestern.objects.filter(water_name__contains='Orange') // hard coded for easy testing
のindex.html
です私の州のリンクの
<a id="s06" href="CA">
state.html
{% if county_list %}
<ul>
{% for county in county_list %}
<li><a href="{% url 'main:county' county %}">{{ county }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No counties were found.</p>
{% endif %}
私は、これはすべての状態のための私のDBに列を追加することで解決することができますが、私はこれはかなり簡単に解決することができ、100%確信している、私はどれだけ
感謝を持っているかもしれませんが、私は私の意見/テンプレートに変更するには、正確に何が必要でしょうか?とは、渡される変数のプレースホルダではありませんか? –
jlee
実際、彼らはそれ以上のことはしません。ビューは、クエリセットのフィルタリングなどのために消費する引数を取得します。この回答を参照してください:http://stackoverflow.com/questions/15754122/url-parameters-and-logic-in-django-class- basedview-templateview – karthikr
ちょっとしたやり直しの後、私はこれを動作させることができました、ありがとう! – jlee