【问题标题】:Django url No Activity matches the given query?Django url No Activity 匹配给定的查询?
【发布时间】: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

【问题讨论】:

  • 好吧,蛞蝓myactivity2018这一年没有活动。
  • 代码看起来不错,但这并不意味着 URL 本身是 sensical,您需要在数据库中查询具有 Activity 的 URL 匹配。
  • 该错误提示您查询的是Post,而不是Activity,您确定在此处分享相关部分吗?
  • 对不起,我说错了。重写错误信息
  • 可能是你的数据库没有year=2018的条目,slug='myactivity',你之前确定了吗? manage.py shell 在这方面很方便。

标签: python django django-urls slug


【解决方案1】:

这种方法的唯一问题是,如果你不指定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,那么我们添加一个额外的过滤器。

但我发现year 过滤器相当奇怪:对于给定的year,通常会有多个 Activitys,所以这会出错。

如果您收到如下错误:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-06-03
    • 2021-04-25
    • 2015-08-04
    • 1970-01-01
    • 2016-01-31
    • 2017-03-08
    • 1970-01-01
    • 2013-09-22
    • 2011-08-19
    相关资源
    最近更新 更多