2013-05-14 2 views
4

어떻게 장고에서 URL 호출을 중첩합니까? 나는 두 가지 모델이있는 경우 예를 들어, 다음 URL을 파일로장고에 중첩 된 URL

class Post(models.Model): 
    title = models.CharField(max_length=50) 
    body = models.TextField() 
    created = models.DateTimeField(auto_now_add=True, editable=False) 


    def __unicode__(self): 
     return self.title 

    @property 
    def comments(self): 
     return self.comment_set.all() 

class Comment(models.Model): 
    comment = models.TextField() 
    post = models.ForeignKey(Post) 
    created = models.DateTimeField(auto_now_add=True) 

로 정의

루트 URL

urlpatterns = patterns('', 
    url(r'^post/', include('post.urls')), 
) 

포스트 URL

urlpatterns = patterns('', 
    url(r'^$', views.PostList.as_view()), 
    url(r'^(?P<pk>[0-9]+)/$', views.PostDetail.as_view()), 
    url(r'^(?P<pk>[0-9]+)/comments/$', include('comment.urls')), 
) 

코멘트 URL

urlpatterns = patterns('', 
    url(r'^$', CommentList.as_view()), 
    url(r'^(?P<pk>[0-9]+)/$', CommentDetail.as_view()), 
) 
나는이 비록 문제가되지 않습니다

Using the URLconf defined in advanced_rest.urls, Django tried these URL patterns, in this order: 
^post/ ^$ 
^post/ ^(?P<pk>[0-9]+)/$ 
^post/ ^(?P<pk>[0-9]+)/comments/$ 
The current URL, post/2/comments/1, didn't match any of these. 

을 진술/후/2/댓글/1, 내가 주어진 오전 페이지를 찾을 수 없습니다 오류에 갈 때 나는/후/2/댓글을 방문 할 때

그러나 이것은인가 django에서 중첩 된 URL 호출을 허용하지 않습니까?

답변

11

는 아마도 : 따라서, 당신은에 정규 표현식을 업데이트해야합니다. 달러 기호없이이 줄을보십시오 :

... 
url(r'^(?P<pk>[0-9]+)/comments/', include('comment.urls')), 
... 

희망이 있습니다!

+0

Woops, 고마워요! – user1876508

+0

당신을 가장 환영합니다! :) –

6

r'^(?P<pk>[0-9]+)/comments/$' 끝에 $이 있습니다.

즉, Django는 그 이후에 아무것도없는 경우에만 해당 URL과 일치합니다.

이제는 더 이상 긴 URL이 고려되지 않습니다. 당신은 달러 기호 $와 정규식을 마무리하고 있기 때문에 내가 생각

url(r'^(?P<pk>[0-9]+)/comments/', include('comment.urls')),