use*_*508 5 python django django-urls
如何在django中嵌入网址?例如,如果我将两个模型定义为
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)
Run Code Online (Sandbox Code Playgroud)
使用以下url文件
根网址
urlpatterns = patterns('',
url(r'^post/', include('post.urls')),
)
Run Code Online (Sandbox Code Playgroud)
发布网址
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')),
)
Run Code Online (Sandbox Code Playgroud)
评论网址
urlpatterns = patterns('',
url(r'^$', CommentList.as_view()),
url(r'^(?P<pk>[0-9]+)/$', CommentDetail.as_view()),
)
Run Code Online (Sandbox Code Playgroud)
但是当我转到/ post/2/comments/1时,我发现了一个Page not not found错误
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.
Run Code Online (Sandbox Code Playgroud)
这不是问题,但是当我访问/发布/ 2 /评论django不允许这样的嵌套URL调用吗?
Pau*_* Bu 12
我想可能是因为你用美元符号完成了正则表达式$
.尝试没有美元符号的这一行:
...
url(r'^(?P<pk>[0-9]+)/comments/', include('comment.urls')),
...
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
你有一个$
结束r'^(?P<pk>[0-9]+)/comments/$'
.
这意味着Django只会在之后没有任何内容时匹配该URL.
因此,目前不再考虑任何更长的网址.因此,您需要将正则表达式更新为:
url(r'^(?P<pk>[0-9]+)/comments/', include('comment.urls')),
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4504 次 |
最近记录: |