在Django中创建分层URL

时间:2017-05-20 14:42:47

标签: python django

我第一次涉足django而且我被困在一个问题上,这让我发疯了。我正在尝试使用像www.example.com/{state}/{county}这样的分层网址创建一组网页。基本上我遇到的问题是我可以获得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%确定这可以很简单地解决,我只是不确定如何

1 个答案:

答案 0 :(得分:2)

您对县的网址模式略有偏差:

url(r'^(?P<state_pk>[A-Z]{2})/(?P<county_pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county')

分层网址模式适用于包含。在这里,它不是嵌套的URL结构,因此它不匹配县,后面跟州,除非你有一个正则表达式模式来匹配它。

另外,请注意正则表达式模式名称的更改 - 您可能需要相应地调整视图和模板

相关问题