我正在使用django 1.9。在实现基于类的视图和urlpatterns时,我无法将我的特定链接重定向到相应的帖子。
设置/ urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from posts.views import Home
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^post/', include("posts.urls")),
url(r'^$', Home.as_view(), name="blog_home"),
]
文章/ urls.py
from django.conf.urls import url, include
from .views import Display
urlpatterns = [
url(r'^(?P<slug>\w+)/$', Display.as_view(), name="get_post"),
]
文章/ views.py
class Display(View):
def get(self, request, slug):
params = {}
params['post'] = Post.objects.get(slug=slug)
return render(request, "blog/viewpost.html", params)
def post(self, request):
pass
我的错误如下:
答案 0 :(得分:2)
当您使用网址正则表达式-gsd
时,r'^(?P<slug>\w+)/$
会匹配字母数字字符和下划线。但是,它不会匹配连字符\w
。
因此,当您的模板查找-
等于slug
的网址时,上述正则表达式将找不到匹配项。你应该尝试使用它:
sample-post