【发布时间】:2019-03-06 08:46:29
【问题描述】:
我正在尝试编写一个 slug 字段,以便用户可以查看我的 activity_detail 页面。我想我写的代码是对的,但是No Activity matches the given query.
出现 404 错误。这是我的代码:
我的 urls.py
from django.urls import re_path
from . views import activity_list, activity_detail, activity_index
app_name = 'activity'
urlpatterns = [
re_path(r'^$', activity_index, name='index'),
re_path(r'^(?P<year>[0-9]{4})/$', activity_list, name='list'),
re_path(r'^(?P<year>[0-9]{4})/(?P<slug>[\w-]+)/$', activity_detail, name='detail'),
]
我的意见.py:
def activity_detail(request, year, slug=None):
activity = get_object_or_404(Activity, year=year, slug=slug)
context = {
'activity': activity,
}
return render(request, "activity/detail.html", context)
我打算从浏览器中调用我的url地址如下:
http://localhost/activity/
http://localhost/activity/2018/
http://localhost/activity/2018/myactivity
【问题讨论】:
-
好吧,蛞蝓
myactivity和2018这一年没有活动。 -
代码看起来不错,但这并不意味着 URL 本身是 sensical,您需要在数据库中查询具有
Activity的 URL 匹配。 -
该错误提示您查询的是
Post,而不是Activity,您确定在此处分享相关部分吗? -
对不起,我说错了。重写错误信息
-
可能是你的数据库没有year=2018的条目,slug='myactivity',你之前确定了吗? manage.py shell 在这方面很方便。
标签: python django django-urls slug