首页 > 解决方案 > Django url No Activity 匹配给定的查询?

问题描述

我正在尝试编写一个 slug 字段,以便用户可以查看我的activity_detail页面。我想我写的代码是对的,但是我得到了 404 错误No Activity matches the given query. 。这是我的代码:

我的网址.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

标签: pythondjangodjango-urlsslug

解决方案


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

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

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

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

但是我发现过滤器很奇怪:通常给定的 syear会有多个 ,所以这会出错。Activityyear

如果您收到如下错误:

没有活动与给定的查询匹配。

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

如果要显示与过滤器匹配的所有Activitys,可以使用get_list_or_404[Django-doc]


推荐阅读