python - Django 在通用 View 中抛出 404

标签 python django http-status-code-404 django-generic-views

我正在尝试获取在 django 中工作的基于日期的存档的通用 View 。 我按照教程中的描述定义了 url,但是只要我想访问其中包含变量(例如月份或年份)的 url,django 就会返回 404 错误。它甚至不会产生 TemplateDoesNotExist 异常。没有变量的普通 url 工作正常。

这是我的更新 urlconf:

from django.conf.urls.defaults import *
from zurichlive.zhl.models import Event

info_dict = {
        'queryset': Event.objects.all(),
        'date_field': 'date',
        'allow_future': 'True',
}

urlpatterns += patterns('django.views.generic.date_based',
    (r'events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug', template_name='archive/detail.html')),
    (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, template_name='archive/list.html')),
    (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$','archive_day',dict(info_dict,template_name='archive/list.html')),
    (r'^events/(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month', dict(info_dict, template_name='archive/list.html')),
    (r'^events/(?P<year>)/$','archive_year', dict(info_dict, template_name='archive/list.html')),
    (r'^events/$','archive_index', dict(info_dict, template_name='archive/list.html')),
)

当我访问/events/2010/may/12/this-is-a-slug/时,我应该访问detail.html模板,但我却得到了404。我做错了什么?

我使用的是 Django 1.1.2

最佳答案

您忘记了正则表达式中的反斜杠:

(r'events/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$'

此外,您还(正确地)获得了以斜杠结尾的 URL 正则表达式,因此您的 URL 应为 /events/2010/may/12/this-is-a-slug/

关于python - Django 在通用 View 中抛出 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2818073/

相关文章:

python - 在 django ORM、自定义查询集字段中使用计数和聚合(Sum)

c# - 我怎样才能 catch 404?

spring - 使用 Spring DispatcherServlet 自定义 404

python - 根据行号列表合并数据帧

python - 用户输入以使用 BioPython 检查 DNA 序列的限制性位点

python - 如何使用 NLTK 正则表达式模式用 UP/DOWN 指标注释财经新闻?

python - 我如何断言该参数仅包含 Python 中列出的整数

python - Django 模型表单集在 POST 上非常慢

python - Django - 为什么在模型类静态中声明变量

python - Flask 路由在 URL 中给出带有 float 的 404