You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何为CategoryViewSet配置product urls.py及核心urls.py路径?

解决CategoryViewSet的URL配置问题

你的核心urls.py配置是正确的,问题出在products模块的urls.py里——同时混用了路由注册和手动视图映射,还错误地在path中使用正则语法。以下是修正方案:

修正products/urls.py

保留DefaultRouter的注册逻辑,去掉冲突的手动路由,正确包含路由器生成的URL:

from django.urls import path, include
from rest_framework import routers
from .views import ProductList, AddProduct, ProductDetails, CategoryViewSet

# 初始化默认路由器并注册分类视图集
router = routers.DefaultRouter()
router.register(r'categories', CategoryViewSet)

urlpatterns = [
    # 原有产品相关路由
    path('list/', ProductList.as_view(), name="View Product"),
    path('add/', AddProduct.as_view(), name="Create Product"),
    path('<int:pk>/', ProductDetails.as_view(), name="product_detail"),
    # 包含路由器生成的分类CRUD路由,建议放在最后避免匹配冲突
    path('', include(router.urls)),
]

核心urls.py无需修改

你当前的core/urls.py配置已经正确将/api/product/路径指向products模块的URL配置,保持原样即可:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/product/', include('products.urls')),
    path('api/user/', include('user.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns = format_suffix_patterns(urlpatterns)

可用的分类CRUD路径

DefaultRouter会自动为CategoryViewSet生成完整的RESTful路由:

  • 分类列表:GET /api/product/categories/
  • 创建分类:POST /api/product/categories/
  • 分类详情:GET /api/product/categories/<pk>/
  • 更新分类:PUT /api/product/categories/<pk>/(全量更新)或PATCH /api/product/categories/<pk>/(部分更新)
  • 删除分类:DELETE /api/product/categories/<pk>/

原代码的问题说明

  1. path(r'^', include(router.urls)):path不支持正则表达式语法,应该用path('', include(router.urls)),直接用空path即可让路由器接管匹配剩余路径。
  2. 手动添加的re_path(r'categories/', ...)会和路由器生成的路由冲突,因为路由器已经处理了categories开头的所有CRUD路径,无需重复配置。

内容的提问来源于stack exchange,提问作者DarkHorse_906

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 21:35:16