【发布时间】:2017-10-20 14:18:22
【问题描述】:
我是第一次涉足 django,但我被困在一个问题上,这让我发疯。我正在尝试创建一组具有像 www.example.com/{state}/{county} 这样的分层 url 的页面。基本上我遇到的问题是我可以获得www.example.com/{state},但我不知道如何使用 django 中的 url 系统将状态转移到州/县页面。我最终得到的是www.example.com//{county}
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 %}
我意识到这可以通过在我的数据库中为状态添加一列来解决,但我 100% 确信这可以很简单地解决,我只是不确定如何
【问题讨论】: