NoReverseMatch的Django错误
我是一名学习python django的学生 在下面的错误消息中遇到我NoReverseMatch的Django错误,django,django-urls,Django,Django Urls,我是一名学习python django的学生 在下面的错误消息中遇到我 NoReverseMatch at / Reverse for 'product' with arguments '(2,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$(?P<pk>[0-9]+)$'] 您需要将project\u root/project/url.py中的url(r'^$,include('shops.url',
NoReverseMatch at /
Reverse for 'product' with arguments '(2,)' and keyword arguments '{}' not found.
1 pattern(s) tried: ['$(?P<pk>[0-9]+)$']
您需要将
project\u root/project/url.py中的url(r'^$,include('shops.url',namespace=“shops”),
更改为url(r'^',include('shops.url',namespace=“shops”),
$
表示使用与前面的$
完全相同的字符匹配字符串,因此,当您的项目根/shops/url.py中有pk时,不会考虑pk,因为原始url中指定的$
,其中包含所有项目根/shops/url.py会缩短正则表达式
这也许可以用更好的措辞。。。但希望你能明白这一点。用于包含其他url文件的url几乎不应该包含$
尝试将项目根/project/url.py
第一个url更改为url(r'^',include('shops.Urls',namespace=“shops”),
它可以工作。。。非常感谢没问题!我在下面留下了一个答案,试图解释为什么会这样。您可以继续接受它,以表明它有帮助:)
<!-- ** error occurs at this point ** -->
<li><a href="{% url 'shops:product' category.id %}" >
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,
}),
]
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'),
]
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