Django嵌套URL [英] Django nested URLs

查看:114
本文介绍了Django嵌套URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Django中嵌套url调用?例如,如果我有两个定义为

How do I nest 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)

带有以下网址文件

根网址

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

发布网址

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

评论网址

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

但是当我转到/post/2/comments/1时,出现页面未找到错误,指出

But when I go to /post/2/comments/1, I am given a Page not found error stating

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.

虽然当我访问/post/2/comments时这不是问题,但是django是否不允许这样的嵌套URL调用?

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

推荐答案

我认为可能是因为您正在用美元符号 $ 完成正则表达式.尝试以下不带美元符号的行:

I think is probably because you're finishing the regex with the dollar sign $. Try this line without the dollar sign:

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

希望有帮助!

这篇关于Django嵌套URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆