Reputation: 3175
I'm dabbling in django for the first time and I'm stuck on one single issue and it's driving me crazy. I'm trying to create a set of pages with a hierarchical url like this www.example.com/{state}/{county}
. Basically the problem I'm having is that I can get www.example.com/{state}
, but I don't know how to use the url system in django to carry the state over to the state/county page. What I end up getting is 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
this file is large so I'll just show an example of one of my state links
<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 %}
I realize this can all be solved by adding a column in my db for the state but I'm 100% sure this can be solved pretty simply, I'm just not sure how
Upvotes: 0
Views: 606
Reputation: 99640
Your url pattern for county is slightly off:
url(r'^(?P<state_pk>[A-Z]{2})/(?P<county_pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county')
Hierarchical URL patterns would work with inclusions. Here, it is not a nested URL structure, so it would not match the county, followed by state unless you have a regex pattern to match that.
Also, note the change of the regex pattern name - you might have to tweak your views and templates accordingly
Upvotes: 4