使用 URL 按类别过滤服务时找不到 Django 页面(404)

Django Page not found (404) when filter services by categories using urls

我正在学习如何在 Django 中使用 urls,但我遇到了问题。我试图通过单击类别 link 来获取属于某个类别的所有服务,但是当我这样做时,浏览器 returns 给我这个错误:

Page not found (404)
   Request Method:  GET
      Request URL:  http://localhost:8000/services/None
         Raised by: services_app.views.service_list
No Category matches the given query.

url 看起来:

http://localhost:8000/services/None

我已经有一个填充的数据库,它可以只使用 djanfo 来显示它们的内容,但我需要它按类别显示。谁能帮帮我?

这是我的文件:

home_app/models.py

from django.db import models
from django.urls import  reverse

class Category(models.Model):
    name=models.CharField(primary_key=True, max_length=50)
    slug=models.SlugField(unique=True, blank=True, null=True)
    image=models.ImageField(upload_to='category_home')
    description=models.CharField(max_length=100)
    content=models.TextField(max_length=500, default="Service")
    created=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('services_by_category', args=[self.slug])

services_app/models.py

from django.db import models
from home_app.models import Category

class Services(models.Model):
    category=models.ForeignKey(Category, on_delete=models.CASCADE)
    title=models.CharField(max_length=50)
    completed=models.DateField(auto_now_add=False, null=True, blank=True)
    content=models.CharField(max_length=50, null=True, blank=True)
    image=models.ImageField(upload_to='services_services')
    created=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Service'
        verbose_name_plural = 'Services'
    
    def __str__(self):
        return '%s de %s' % (self.category, self.title)

services_app/views.py

from django.shortcuts import render, get_object_or_404
from .models import Services
from home_app.models import Category

def service_list(request,category_slug=None):
    category = None
    categories = Category.objects.all()
    services = Services.objects.all()
    if category_slug:
        category = get_object_or_404(Category,slug=category_slug)
        services = services.filter(category=category)
    return render(request, 'services_app/services.html', {'categories':categories, 'category':category, 'services':services,})

services_app/urls.py

from django.urls import path
from services_app import views

urlpatterns = [
    path('', views.service_list, name='Services'),
    path('<slug:category_slug>', views.service_list, name='services_by_category'),
]

services_app/templates/services_app/services.html

{% extends "home_app/base.html" %}
{% load static %}
{% block content %}

<div id="sidebar">
    <br>
    <br>
    <h3>Categories</h3>
        <ul>
        {% for c in categories %}
            <li>
           <h4><a href="{{ c.get_absolute_url }}">{{ c.name }}</a></h4>
            </li>
        {% endfor %}
        </ul>
</div><br>
<div>
    <h1>{% if category %}{{ category.name }}{% endif %}</h1>
    {% for service in services %}
        <img src="{{service.image.url}}">
    {% endfor %}
</div>

{% endblock %}

也是我的主要 urls:

from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home_app.urls')),
    path('services/', include('services_app.urls')),
    path('contact/', include('contact_app.urls')),
]

问题是您没有生成 Category 的 slug:

from django.db import models
from django.urls import  reverse
from django.utils.text import slugify

class Category(models.Model):
    name=models.CharField(primary_key=True, max_length=50)
    slug=models.SlugField(unique=True, blank=True, null=True)
    image=models.ImageField(upload_to='category_home')
    description=models.CharField(max_length=100)
    content=models.TextField(max_length=500, default="Service")
    created=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'
 
    def save(self, *args, **kwargs):
        if self._state.adding:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('services_by_category', args=[self.slug])

请注意,您需要手动设置 现有 Category 个实例(通过管理员、shell 或迁移),或者您可以简单地重新创建它们。