Django url 没有 Activity 匹配给定的查询?

Django url No Activity matches the given query?

我正在尝试编写一个 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'),
]

我的views.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

此方法的唯一问题是,如果您未指定 slug,则将使用 slug=None 调用视图,然后使用 slug=None 进行过滤,这会失败。

您可以通过 None 检查解决此问题:

def activity_detail(request, year, slug=None):
    filter = {'year': year}
    if <b>slug is not None</b>:
        filter['slug'] = slug
    activity = get_object_or_404(Activity, <b>**filter</b>)
    context = {
        'activity': activity,
    }
    return render(request, "activity/detail.html", context)

所以这里我们首先创建一个初始的filter字典,它只包含year,如果slug不是None,那么我们添加一个额外的过滤器。

不过我发现 year 过滤器相当奇怪:对于给定的 year,通常会有 多个 Activity,那么这会出错。

如果您遇到如下错误:

No Activity matches the given query.

这意味着在您的数据库中 没有 具有给定年份和 slug 的记录。 404 错误不是问题:它只是表示对于给定的 URL,没有对应的 Activity 对象可用。所以return这样的错误是有道理的。

如果你想显示所有符合过滤器的Activity,你可以使用get_list_or_404 [Django-doc].