0
NoReverseMatch at /category/1/
Reverse for 'category' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category_id>[0-9]+)/$']

从主页导航到站点类别时会显示此错误。在谷歌搜索中,我发现我的 url 与模板中的 url 不匹配,django 报告了它。但我仍然不明白哪里出了问题,因为一切都是为了匹配 urls.py 模板而编写的。

urls.py(应用程序文件夹)

from django.urls import path
from .views import *


urlpatterns = [
    path('', home_page, name='home_page'),
    path('category/<int:category_id>', get_category, name='category'),
    path('news/<slug:slug>', view_news, name='news'),
]

urls.py(项目文件夹)

import debug_toolbar
from django.contrib import admin
from django.urls import include, path
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('news.urls')),
    path('ckeditor/', include('ckeditor_uploader.urls')),
    path('__debug__/', include(debug_toolbar.urls)),
]

base.html

{% load news_tags %}

{% get_all_categories as categoies %}
   {% for category in categoies %}
      <li><a href="{% url 'category' category.pk %}" class="nav-link px-2" style="color: rgb(179, 179, 179);">{{ category.title }}</a></li>
   {% endfor %}

index.html(主页)

{% for item in page_obj %}
        <div class="card mb-5">
          <div class="card-header">
            <div class="category_name"> <a href="{% url 'category' item.category_id %}" style="text-decoration: none; color: rgb(93, 92, 92);">{{ item.category }}</a> - {{ item.created_at }}</div>
          </div>
          <a href="/news/{{ item.slug }}" style="text-decoration: none; color: rgb(26, 25, 25);">
            <div class="card-body">
              <h3 class="card-title">{{ item.title }}</h3>
              <p class="card-text">{{ item.content|linebreaks|truncatewords:50 }}</p>
            </div>
          </a>
        </div>
{% endfor %}

视图.py

def home_page(request):
    all_publicated_blogs = News.objects.filter(is_published=True,)

    return render(request, 'news/index.html', 
                  {'page_obj': Pagination(request, all_publicated_blogs).pagination(10),})


def get_category(request, category_id):
    news_by_category = News.objects.filter(category_id=category_id, is_published=True)
    one_news = news_by_category[0]
    
    return render(request, 'news/category.html', 
                  {'page_obj': Pagination(request, news_by_category).pagination(10), 'news': one_news,})

模型.py

from django.db import models
from ckeditor.fields import RichTextField


class News(models.Model):

    title = models.CharField(max_length=50,verbose_name='Заголовок',)
    content = RichTextField()
    created_at = models.DateTimeField(auto_now_add=True,verbose_name='Дата Создания')
    updated_at = models.DateTimeField(auto_now=True)
    is_published = models.BooleanField(default=False, verbose_name='Опубликовано')                    
    category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, verbose_name='Категория')
    slug = models.SlugField(verbose_name='URL', max_length=40, unique=True,)


    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Новость'
        verbose_name_plural = 'Новости'
        ordering = ['-created_at']


class Category(models.Model):
    title = models.CharField(max_length=50, db_index=True,
                             verbose_name='Название категории')                         

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Категорию'
        verbose_name_plural = 'Категории'
        ordering = ['id']

news_tags.py

from django import template
from news.models import Category


register = template.Library()


@register.simple_tag()
def get_all_categories():
    return Category.objects.all()

类别.html

{% get_all_categories as categoies %}
            {% for category in categoies %}
                {% if category == news.category %}
                  <li><a href="{% url 'category' category_id=category.pk %}" class="nav-link px-2" style="color: white;display: inline; padding: 17px 6px; border-bottom: solid 5px #707990;">{{ category.title }}</a></li>
                {% else %}
                  <li><a href="{% url 'category' category_id=category.pk %}" class="nav-link px-2" style="display: inline; padding: 0px 6px;">{{ category.title }}</a></li>
                {% endif %}
            {% endfor %}
4

1 回答 1

1

我认为index.html在 url 标签中对类别的引用已关闭。更改href="{% url 'category' item.category_id %}"href="{% url 'category' item.category.id %}"

于 2021-08-28T17:50:30.617 回答