snakesNbronies
snakesNbronies

Reputation: 3910

django - url patterns and if-else view

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.

Upvotes: 0

Views: 2405

Answers (1)

Alasdair
Alasdair

Reputation: 308779

You have made the trailing slashes optional, but your regex still requires at least one character for the section argument.

Try changing

(?P<section>[\w\.-]+)

to

(?P<section>[\w\.-]*)

Personally, I find it clearer to declare two URL patterns instead of one with an optional parameter.

url(r'^(?i)book/(?P<chapter>[\w\.-]+)/$', 'book.views.chaptersection'),
url(r'^(?i)book/(?P<chapter>[\w\.-]+)/(?P<section>[\w\.-]+)/$', 'book.views.chaptersection'),

This requires a small adjustment to your chaptersection view to make section an optional argument:

def chaptersection(request, chapter, section=None):

Upvotes: 2

Related Questions