Django购物车模块遇NoReverseMatch及404错误,URL路由问题求助
I’ve dealt with this exact routing quirk in Django before—let’s break down what’s going wrong and get your cart URLs working properly again.
The Core Issue
Your project’s root URL config for the cart app has a regex pattern that’s too broad. The line url(r'^cart', include('cart.urls', namespace='cart')) matches any URL starting with "cart" (think /cart, /cartoon, even /cart123), which causes messy routing conflicts. When you tried adding a trailing slash, it didn’t fix things because the root pattern wasn’t properly restricting matches to /cart/ and its subpaths.
Step 1: Fix the Root URL Configuration
Update your project’s main urls.py to add a trailing slash to the cart route. This ensures only URLs starting with /cart/ get routed to your cart app:
urlpatterns = [ url(r'^', include('shop.urls', namespace='shop')), # Add the trailing slash here to lock down the cart route url(r'^cart/', include('cart.urls', namespace='cart')), url(r'^admin/', include(admin.site.urls)), ]
Step 2: Confirm Your Cart App URLs Are Correct
Your cart app’s urls.py is already set up right—let’s just make sure it aligns with the updated root route:
from django.conf.urls import url from . import views urlpatterns = [ # Matches /cart/ (the cart homepage) url(r'^$', views.cart_detail, name='cart_detail'), # Matches /cart/add/1/ (for adding product ID 1) url(r'^add/(?P<product_id>\d+)/$',views.cart_add,name='cart_add'), # Matches /cart/remove/1/ (for removing product ID 1) url(r'^remove/(?P<product_id>\d+)/$',views.cart_remove,name='cart_remove'), ]
Step 3: Why This Fixes Your Errors
- NoReverseMatch Gone: When your views call
redirect('cart:cart_detail'), Django can now correctly reverse the URL to/cart/instead of trying to generate/cart(without a slash), which didn’t map to any valid route in your cart app. - 404s Fixed: The updated root pattern ensures
/cart/routes directly to yourcart_detailview. Django’s defaultAPPEND_SLASHsetting (turned on by default) will even automatically redirect anyone who visits/cart(no slash) to/cart/, so you don’t have to handle both URL versions.
Quick Checks to Wrap Up
- Clear your browser cache (old cached URLs can cause weird behavior)
- Double-check your templates are using the correct namespace URLs, like
{% url 'cart:cart_add' product.id %} - If you’re using Django’s cache framework, clear that too to make sure the new routing rules load immediately
内容的提问来源于stack exchange,提问作者Mohammad

