I am trying to construct (somewhat RESTFul) URL’s in django 1.4 that will allow filtering by book chapter, and then also book chapter and section. However, as of right now, only the specific chapter and section URL’s return information. When I just input a chapter, the page displays without any content.
My urlpatterns in settings.py:
url(r'^(?i)book/(?P<chapter>[\w\.-]+)/?(?P<section>[\w\.-]+)/?$', 'book.views.chaptersection'),
My views.py:
from book.models import contents as C
def chaptersection(request, chapter, section):
if chapter and section:
chapter = chapter.replace('-', ' ')
section = section.replace('-', ' ')
info = C.objects.filter(chapter__iexact=chapter, section__iexact=section).order_by('symb')
context = {'info':info}
return render_to_response('chaptersection.html', context, context_instance=RequestContext(request))
elif chapter:
chapter = chapter.replace('-', ' ')
info = C.objects.filter(chapter__iexact=chapter).order_by('symb')
context = {'info':info}
return render_to_response('chaptersection.html', context, context_instance=RequestContext(request))
else:
info = C.objects.all().order_by('symb')
context = {'info':info}
return render_to_response('chaptersection.html', context, context_instance=RequestContext(request))
Again… the URL at “book/1/1” for chapter 1 section 1 works fine, but not “book/1”, which should technically show all of chapter 1. I am not getting an error, but at the same time, nothing is being displayed on the screen.
You have made the trailing slashes optional, but your regex still requires at least one character for the section argument.
Try changing
to
Personally, I find it clearer to declare two URL patterns instead of one with an optional parameter.
This requires a small adjustment to your
chaptersectionview to makesectionan optional argument: