【问题标题】:Django NoReverseMatch Reverse for 'cart-add' with arguments '('',)' not found没有找到带有参数'('',)'的'cart-add'的Django NoReverseMatch Reverse
【发布时间】:2018-09-10 06:01:53
【问题描述】:

将href="{% url 'cart-add' product.id %}" 添加到product.html 文件上的添加到购物车按钮后,我收到以下错误:

NoReverseMatch at /3/
Reverse for 'cart-add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[0-9]+)\\/$']

我认为这是一个 url 路径问题或设置,但我不知道如何解决它。如果有我错过的相关文件在这里显示,这里是我的 github:https://github.com/sebapaik/django-shop

我的 product.html 文件如下所示:

{% extends "shop/base.html" %}
{% block content %}
  <div class="container">
    <div class="row">
        <div class="col-lg-4">
          <img class="img-thumbnail" src="{{ object.imageurl }}" alt="">
        </div>
        <div class="col-lg-8">
          <h2>{{ object.brand }} {{ object.pname }}</h2>
          <p>${{ object.price }}</p>
          <p>{{ object.description }}</p>
**likely the problem below**
          <button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' product.id %}">Add to cart</button>
        </div>
      </div>
    {% endblock content %}

我的项目/urls.py(主)如下所示:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('shop.urls')),
    path('cart/', include('cart.urls')),
]

我的商店/urls.py 如下所示:

from django.urls import path
from .views import ProductListView, ProductDetailView
from . import views

urlpatterns = [
    path('', ProductListView.as_view(), name = 'shop-index'),
    path('<int:pk>/', ProductDetailView.as_view(), name = 'shop-product'),
]

我的购物车/urls.py 如下所示:

from django.urls import path
from . import views

urlpatterns = [
    path('add/<int:product_id>/', views.add_cart, name='cart-add'),
    path('', views.cart_detail, name='cart-detail'),
]

我的 settings.py 如下所示:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@9k!nb!1wi5*d=+*#3j+$gl%(#$z(c1aqsyh1p+qqs@)yeuh*_'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'shop.apps.ShopConfig',
    'cart.apps.CartConfig',
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

CRISPY_TEMPLATE_PACK = 'bootstrap4'

我正在使用 Django 2.1.1、Python 3.6 和 Windows 10

【问题讨论】:

  • 我猜你想写href="{% url 'cart:cart-add' object.id %}"而不是href="{% url 'cart:cart-add' product.id %}"。我不确定 product 是否传递给视图?

标签: python python-3.x django url


【解决方案1】:

根据错误消息,您的product.id 为空。您应该在模板中使用object.id:

<button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' object.id %}">Add to cart</button>

【讨论】:

  • 我收到此错误:NoReverseMatch at /3/ 'cart' is not a registered namespace。我不确定为什么不识别购物车应用程序。它在设置中。
【解决方案2】:

似乎 Django 识别出你的请求 url 是'/3/',你想要反转的是'car/add/3/',你可以尝试简单地使用 [href="/cart-add/{{product .id}}'"] 来替换 [href="{% url 'cart-add' product.id %}"]。顺便说一下,你的 'shop/urls.py' 和 'cart/urls.py'具有相同的行“路径('add//',views.add_cart,name='cart-add')”?这可能会导致一些其他问题。

【讨论】:

  • 抱歉打错了。我两次粘贴了相同的 urls.py 文件。我已经尝试了@blhsing 的建议,但现在我遇到了命名空间识别错误。
猜你喜欢
  • 2023-03-15
  • 2012-10-23
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
相关资源
最近更新 更多