首页 > 解决方案 > 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>

标签: pythondjango

解决方案


您的错误由: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 %}

如果你错过了什么,我可以用土耳其语解释;)


推荐阅读