【问题标题】:Django Error for NoReverseMatchNoReverseMatch 的 Django 错误
【发布时间】:2014-12-29 08:16:27
【问题描述】:

我是一名学习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/shops/templates/shops/base.html

 <!-- **  error occurs at this point  ** -->
 <li><a href="{% url 'shops:product' category.id %}" >

project_root/project/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/shops/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/shops/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

【问题讨论】:

  • 尝试将您的project_root/project/urls.py 第一个网址更改为url(r'^', include('shops.urls', namespace="shops")),
  • 它有效...非常感谢! :D
  • 没问题!我在下面留下了一个答案,试图解释为什么会解决这个问题。你可以继续接受它以表明它有帮助:)

标签: django django-urls


【解决方案1】:

您需要将 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 的原始 url 中指定的 987654325@ 会缩短正则表达式。

这可能措辞更好......但希望你明白这一点。用于包含其他 url 文件的 URL 几乎不应该包含 $

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 2017-07-30
    • 2017-03-14
    相关资源
    最近更新 更多