【发布时间】:2020-11-15 22:42:45
【问题描述】:
您能帮我理解以下错误吗? 我正在学习 Django,并且确实坚持使用视图的反向渲染。 当我点击产品链接时,它应该会转到产品页面,但会抛出错误。
我的分析 我在产品单一功能中插入了打印语句,并且可以在终端中看到该程序可以正常工作,直到它渲染视图,这有帮助吗?
从终端
15/Nov/2020 22:49:59] "GET /products/ HTTP/1.1" 200 7582
<WSGIRequest: GET '/products/product-3/'>
{'product': <Product: Product 3>, 'images': <QuerySet []>}
products/single.html
Internal Server Error: /products/product-3/
Traceback (most recent call last):
错误
/products/product-3/ 处的 NoReverseMatch
找不到“add_to_cart”的反向。 'add_to_cart' 不是有效的视图函数或模式名称。
请求方法:GET
请求网址:http://127.0.0.1:8000/products/product-3/
Django 版本:3.1.3
异常类型:NoReverseMatch
异常值:
找不到“add_to_cart”的反向。 'add_to_cart' 不是有效的视图函数或模式名称。
HTML
{% extends "base.html" %} {% block content %}
<h1>Search for {{ query }}</h1>
{{ product }}
<table class="table">
<thead>
<th></th>
<th>Product</th>
</thead>
<tbody>
{% for product in product_htm %}
<tr>
<td>Image</td>
<td><a href="{ product.get_absolute_url }}"> {{ product }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
产品应用中的models.py
# Create your models here.
class Product(models.Model):
def get_absolute_url(self):
return reverse("product_app:single_product", kwargs={"slug": self.slug})
products views.py
def single(request, slug):
product = Product.objects.get(slug=slug)
images = ProductImage.objects.filter(product=product)
context = {'product': product, 'images': images}
template = 'products/single.html'
print(request)
print(context)
print(template)
return render(request, template, context)
产品应用 urls.py 从 。导入视图
app_name = 'product_app'
urlpatterns = [
path('', views.index, name='home'),
path('s/', views.search),
path('products/', views.all, name='products'),
path('products/<slug:slug>/', views.single, name='single_product'),
]
购物车 urls.py
from . import views
# import (index, ProductSingleView)
app_name = 'cart_app'
extra_patterns = [
path('cart/carts/<slug:slug>/', views.add_to_cart),
]
urlpatterns = [
path('cart/', include(extra_patterns), name='add_to_cart'),
path('cart/<int:id>', views.remove_from_cart, name='remove_from_cart'),
path('', views.view, name='cart'),
]
carts views.py
# Create your views here.
from products.models import Product, Variation
from .models import Cart, CartItem
def view(request):
try:
the_id = request.session['cart_id']
except DoesNotExist:
the_id = None
if the_id:
cart = Cart.objects.get(id=the_id)
new_total = 0.00
for item in cart.cartitem_set.all():
line_total = float(item.product.price) * item.quantity
new_total += line_total
request.session['items_total'] = cart.cartitem_set.count()
cart.total = new_total
cart.save()
context = {"cart": cart}
else:
empty_message = "Yout cart is empty, please keep shopping"
context = {"empty": True, "empty_message": empty_message}
template = "cart/view.html"
return render(request, template, context)
def remove_from_cart(request, id):
try:
the_id = request.session['cart_id']
cart = Cart.objects.get(id=the_id)
except:
return HttpResponseRedirect(reverse('cart_app:cart'))
cartitem = CartItem.objects.get(id=id)
cartitem.cart = None
cartitem.save()
return HttpResponseRedirect(reverse('cart_app:cart'))
def add_to_cart(request, slug):
request.session.set_expiry(120)
try:
the_id = request.session['cart_id']
except:
new_cart = Cart()
new_cart.save()
request.session['cart_id'] = new_cart.id
the_id = new_cart.id
cart = Cart.objects.filter(id=the_id)
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
print("except1")
product_var = []
if request.method == "POST":
qty = request.POST['qty']
for item in request.POST:
key = item
val = request.POST[key]
try:
v = Variation.objects.get(product=product, category__iexact=key, title__iexact=val)
product_var.append(v)
except Variation.DoesNotExist:
pass
cart_item = CartItem.objects.create(cart=cart, product=product)
print("iam here")
if len(product_var) > 0:
# * adds each item
cart_item.variations.add(*product_var)
cart_item.quantity = qty
cart_item.save()
return HttpResponseRedirect(reverse('cart_app:cart'))
else:
return HttpResponseRedirect(reverse('cart_app:cart'))
项目电子商务中的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('', include('products.urls')),
path('cart/', include('carts.urls'), name='cart'),
path('admin/', admin.site.urls),
]
【问题讨论】:
-
您可能在模板中对不存在的反向名称进行了反向操作
-
我刚刚在问题中添加了更多信息,希望这能给出一些细节
标签: python django django-views