python - 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
解决方案
这种方法的唯一问题是,如果您不指定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
会有多个 ,所以这会出错。Activity
year
如果您收到如下错误:
没有活动与给定的查询匹配。
因此,这意味着您的数据库中没有记录具有给定年份和 slug。404 错误不是问题:它只是表示对于给定的 URL,没有Activity
可用的相应对象。所以返回这样的错误是有意义的。
如果要显示与过滤器匹配的所有Activity
s,可以使用get_list_or_404
[Django-doc]。
推荐阅读
- excel - VBA复制范围重复
- imagemagick - 调整图像亮度 imagemagick
- sql - postgresql 从具有数据的同一列更新具有 NULL 的列
- javascript - 如果javascript中的某些键相同,则将数组推送到对象中
- php - 使用 laravel 通过 AJAX 上传文件
- selection - Odoo - 从 One2Many 列表中选择项目时触发模型方法
- python - GridSearchCV 使用 SAME 参数的性能比普通 SVM 差
- unity3d - Unity - 让角色在滑下平台时能够跳跃
- c# - POS .net 未发布 MSR
- debugging - 如何将 GDB 输出设置为 stderr?