2012-09-13 2 views
0

장 장별 필터링을 허용하는 django 1.4에서 (다소 RESTFul) URL을 구성하려고합니다. 그런 다음 장과 장도 함께 예약합니다. 그러나 현재로서는 특정 챕터 섹션 URL의 반환 정보 만 있습니다. 방금 장을 입력하면 내용없이 페이지가 표시됩니다. settings.py에서django-url 패턴 및 if-else보기

내 urlpatterns :

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

내 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)) 

다시 ...에서 URL은 제 1 장 제 1 개 절 작품 "/ 1/1 예약" 좋지만 책 1은 기술적으로 모든 장 1을 표시해야합니다. 오류가 발생하지는 않지만 동시에 화면에 아무것도 표시되지 않습니다.

답변

2

후행 슬래시를 선택 사항으로 만들었지 만 정규 인수에 섹션 인수로 적어도 하나 이상의 문자가 필요합니다.

시도 개인적으로

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

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

을 변경, 나는 그것이 명확 두 개의 URL 패턴 대신 선택적 매개 변수 하나를 선언 찾을 수 있습니다.

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

감사합니다 : 당신의 chaptersection보기에

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

이 작은 조정을 필요는 section 선택적 인수를 만들기 위해! 매우 간결하면서도 유익합니다. – snakesNbronies