python - Django Navbar 类别链接问题
问题描述
当我单击菜单中的类别链接时,出现以下错误。
找不到页面 (404)
请求方法:GET
请求网址: http: //127.0.0.1 :8000/post/categorylist/
提出者:post.views.post_detail
没有帖子与给定的查询匹配。
模型.py
def get_categorylist_url(self):
return reverse('post:categorylist', kwargs={'slug': self.slug})
视图.py
def post_categorylist(request, slug):
if not request.user.is_superuser:
raise Http404()
post = get_object_or_404(Post, slug=slug)
post.categorylist()
return redirect('post:categorylist')
网址.py
path('categorylist/',views.post_categorylist, name='categorylist'),
header.html
<li><a href="{% url 'post:categorylist' %}">Kategoriler</a></li>
类别列表.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
Test message.
</body>
</html>
解决方案
您的错误由:post.views.post_detail
所以您的网址错误。您想要获取 slug 参数,但您的 url 没有任何 slug 参数。首先,您应该修复您的 url 路径。
比,如果您想当用户单击 x 类别链接并获取 x 类别中的产品时,让我们举个例子:
首先创建这个视图:
视图.py:
def category_list(request):
# Category loops on index page.
category_list = Category.objects.filter()
context = {
"category_list": category_list,
}
return context
比,我们应该将此上下文添加到我们的上下文处理器中以访问任何地方(因为它是导航栏,所以导航栏将位于每个页面的顶部,对吗?)
设置.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
************************************,
'YOURMODELNAME.views.category_list',
],
},
},
]
最后,您将访问项目中的所有类别,只需在模板中添加以下代码:
导航栏.html:
{% for category in category_list %}
<a href="{% url 'categories' slug=category.slug %}">
{{ category.name }} <!--You can use ul-li for displaying them-->
</a>
{% endfor %}
好的,我们显示了我们的类别,但是当用户点击任何链接时,应该重定向到点击类别中的过滤列表。所以我们应该为这个页面创建页面和链接:
视图.py:
def category_list(request, slug):
category = Category.objects.get(slug=slug)
posts = Post.objects.filter(category=category)
context = {
"posts": posts, #filtered products
}
return render(request, "posts_in_category.html", context)
网址.py:
path('category/<slug:slug>', views.category_list, name="category_list")
post_in_category.html:
{% for post in posts_in_category %}
{{ post.name }}
{% endfor %}
如果你错过了什么,我可以用土耳其语解释;)
推荐阅读
- react-native - 在 FlatList 中使用时,可选文本不起作用
- scala - 线程“主”java.lang.NoClassDefFoundError 中的 Gatling 错误异常:io/gatling/charts/component/impl/ComponentLibraryImpl
- javascript - 如何使用jquery查找和删除数组
- php - foreach 在 foreach 检查数据?
- python - concurrent.futures:如何在 2 个单独的线程中提交任务和处理 Futures?
- python - Selenium webdriver在python中的chrome编码中打开一个新选项卡
- python - 数据传入时更新 json 文件的最佳方法
- php - 在重复密钥更新时……时间戳未更新
- flutter - 如何在颤振(android)中制作这个自定义应用栏?
- javascript - 如何在页面上的特定滚动位置启动功能?