0

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

jlee
  • 2,835
  • 3
  • 16
  • 16

1 Answers1

4

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

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • Thanks for your response, what exactly would I need to change in my views/templates? Aren't and just placeholders for variables that are passed in? – jlee May 20 '17 at 15:08
  • Actually, no they do a little more than that. The view gets the argument, which you would consume for the queryset filtering, etc.. See this answer for example: http://stackoverflow.com/questions/15754122/url-parameters-and-logic-in-django-class-based-views-templateview – karthikr May 20 '17 at 15:10
  • after a bit of tinkering I was able to get this to work, thank you! – jlee May 20 '17 at 15:54
  • Great job.. this is a good part of the learning experience..touching all aspects – karthikr May 20 '17 at 15:55