我是一名学习python django的学生。
我在下面遇到错误消息。
NoReverseMatch at /
Reverse for 'product' with arguments '(2,)' and keyword arguments '{}' not found.
1 pattern(s) tried: ['$(?P<pk>[0-9]+)$']
我试图从昨天开始搜索和搜索,但我真的不知道原因。
您能否给我一个提示或建议?
我使用的Django版本是1.7。
=============================================== ===================================
project_root /商店/模板/商店/ base.html文件
<!-- ** error occurs at this point ** -->
<li><a href="{% url 'shops:product' category.id %}" >
project_root /项目/ urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^$', include('shops.urls', namespace="shops")),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
]
project_root /商店/ urls.py
from django.conf.urls import url
from shops import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)$', views.ProductView.as_view(), name='product'),
]
project_root /商店/ views.py
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.utils import timezone
from shops.models import Sex, Category, Product
class IndexView(TemplateView):
template_name = 'shops/index.html'
def get_context_data(self):
context = super(IndexView, self).get_context_data()
context['sex_list'] = Sex.objects.all()
context['category_list'] = Category.objects.all()
context['latest_product_list'] = Product.objects.order_by('-pub_date')[:5]
return context
class ProductView(ListView):
template_name = 'shops/product_list.html'
def get_context_data(self):
context = super(ProductView, self).get_context_data()
context['product_list'] = Product.objects.all()
return context
答案 0 :(得分:2)
您需要将 project_root / project / urls.py 中的url(r'^$', include('shops.urls', namespace="shops")),
更改为url(r'^', include('shops.urls', namespace="shops")),
$
表示匹配字符串的字符与$
之前的字符完全相同,因此当您在 project_root / shops / urls.py 中有pk时,pk无法获取之所以考虑是因为原始网址中指定的$
包含了所有 project_root / shops / urls.py ,会缩短正则表达式。
这可能措辞得更好......但希望你明白这一点。用于包含其他网址文件的网址几乎不应包含$