我刚刚开始尝试基于Django的类视图,而MonthArchiveView一直很适合我,但当我尝试使用YearArchiveView时,它给了我一条404消息说:
找不到与查询匹配的帖子
我知道应匹配查询的帖子。例如, / blog / 2014 / ,给我404,但 / blog / 2014 / may / 做了它应该做的
#urls.py
from django.conf.urls import patterns, include, url
from django.views.generic import ListView, DetailView
from blog.models import Post
from blog.views import PostMonthArchiveView, PostYearArchiveView
urlpatterns = patterns('blog.views',
# main blog page w/ most recent 5 posts
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-created")[:5],
template_name="blog/list.html"), name="blog"),
url(r'^(?P<slug>[-\w]+)/$', DetailView.as_view(
model=Post,
template_name="blog/post.html"), name="postdetail"),
url(r'^(?P<slug>[-\w]+)$', DetailView.as_view(
model=Post,
template_name="blog/post.html"), name="postdetail"),
# Example: /2012/aug/
url(r'^(?P<year>\d{4})/(?P<month>[-\w]+)/$',
PostMonthArchiveView.as_view(),
name="archive_month"),
url(r'^(?P<year>\d{4})/(?P<month>[-\w]+)$',
PostMonthArchiveView.as_view(),
name="archive_month"),
url(r'^(?P<year>\d{4})/$',
PostYearArchiveView.as_view(),
name="post_year_archive"),
url(r'^(?P<year>\d{4})$',
PostYearArchiveView.as_view(),
name="post_year_archive"),
)
和我的观点
#views.py
from django.shortcuts import render, get_object_or_404
from blog.models import Post
from django.views.generic.dates import MonthArchiveView, YearArchiveView
def post(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, 'blog/post.html', {
'post': post,
})
class PostMonthArchiveView(MonthArchiveView):
queryset = Post.objects.all()
date_field = "created"
make_object_list = True
allow_future = True
class PostYearArchiveView(YearArchiveView):
queryset = Post.objects.all()
date_field = "created"
make_object_list = True
allow_future = True
任何帮助都会很棒,这让我非常头疼,我无法在互联网上找到其他任何东西来尝试帮助排除故障。谢谢!
编辑:使用Django 1.6.2
答案 0 :(得分:0)
如果你仔细查看了你得到的错误,甚至更好地发布了它,你会发现它是由DetailView引起的,而不是YearArchiveView。这是因为URL&#34; / blog / 2014 /&#34;对详细信息网址有效,&#39; ^(?P [ - \ w] +)/ $&#39;,因此在那里被捕获 - 它永远不会进入存档一个。
您可以通过将归档视图的定义移动到详细信息的定义上方来解决此问题,或者可以通过使详细信息正则表达式更具体。