Django Nested URLs

How do I embed url calls in django? For example, if I have two models defined as

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) 

With the following urls

root url

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

post 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')), ) 

comment url

 urlpatterns = patterns('', url(r'^$', CommentList.as_view()), url(r'^(?P<pk>[0-9]+)/$', CommentDetail.as_view()), ) 

But when I go to / post / 2 / comments / 1, I am assigned a page, not found error, indicating

 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. 

This is not a problem, though when I visit / post / 2 / comments Is django allowed to have nested urls like this?

+4
source share
2 answers

I think it’s probably because you end the regular expression with a dollar sign $ . Try this line without a dollar sign:

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

Hope this helps!

+11
source

You have $ at the end of r'^(?P<pk>[0-9]+)/comments/$' .

This means that Django will only match this URL when nothing comes after that.

Thus, no longer URLs are currently considered. Therefore, you need to update the regex to:

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

Source: https://habr.com/ru/post/1480785/


All Articles