gpt4 book ai didi

python - 导入错误位于/cart/;没有名为 'cart.context_processors' 的模块

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:18 25 4
gpt4 key购买 nike

我创建了一个上下文处理器,通过在购物车应用程序目录中创建一个新文件并将其命名为 context_processors.py,将当前购物车设置为模板的请求上下文:

from .cart import Cart
def cart(request):
return {'cart': Cart(request)}

我将“cart.context_processors.cart”添加到 settings.py 文件的 TEMPLATES 设置内的 'context_processors' 选项。这给了我以下错误:

Request Method: GET
Request URL: http://127.0.0.1:8000/cart/

Django Version: 1.9.6
Python Version: 3.5.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'shop',
'cart']


**Traceback:**

File "d:\virEnv\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)

File "d:\virEnv\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\virEnv\myshop\cart\views.py" in cart_detail
31. return render(request, 'cart/detail.html', {'cart': cart})

File "d:\virEnv\lib\site-packages\django\shortcuts.py" in render
67. template_name, context, request=request, using=using)

File "d:\virEnv\lib\site-packages\django\template\loader.py" in render_to_string
97. return template.render(context, request)

File "d:\virEnv\lib\site-packages\django\template\backends\django.py" in render
95. return self.template.render(context)

File "d:\virEnv\lib\site-packages\django\template\base.py" in render
204. with context.bind_template(self):

File "c:\python35-32\Lib\contextlib.py" in __enter__
59. return next(self.gen)

File "d:\virEnv\lib\site-packages\django\template\context.py" in bind_template
256. processors = (template.engine.template_context_processors +

File "d:\virEnv\lib\site-packages\django\utils\functional.py" in __get__
33. res = instance.__dict__[self.name] = self.func(instance)

File "d:\virEnv\lib\site-packages\django\template\engine.py" in template_context_processors
105. return tuple(import_string(path) for path in context_processors)

File "d:\virEnv\lib\site-packages\django\template\engine.py" in <genexpr>
105. return tuple(import_string(path) for path in context_processors)

File "d:\virEnv\lib\site-packages\django\utils\module_loading.py" in import_string
20. module = import_module(module_path)

File "d:\virEnv\lib\importlib\__init__.py" in import_module
126. return _bootstrap._gcd_import(name[level:], package, level)

Exception Type: ImportError at /cart/
Exception Value: No module named 'cart.context_processors'

这是我的 cart\views.py 文件:

from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from shop.models import Product
from .cart import Cart
from .forms import CartAddProductForm

@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
update_quantity=cd['update'])
return redirect('cart:cart_detail')

def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect('cart:cart_detail')

def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(
initial={'quantity': item['quantity'],
'update': True})
return render(request, 'cart/detail.html', {'cart': cart})

这是我的 base.html 文件:

{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{% block title %}My shop{% endblock %}</title>
<link href="{% static "css/base.css" %}" rel="stylesheet">
</head>
<body>
<div id="header">
<a href="/" class="logo">My shop</a>
</div>
<div id="subheader">
<div class="cart">
{% with total_items=cart|length %}
{% if cart|length > 0 %}
Your cart:
<a href="{% url "cart:cart_detail" %}">
{{ total_items }} item{{ total_items|pluralize }},
${{ cart.get_total_price }}
</a>
{% else %}
Your cart is empty.
{% endif %}
{% endwith %}
</div>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>

请给我建议。

编辑:

布局:enter image description here

购物车.py:

from decimal import Decimal
from django.conf import settings
from shop.models import Product

class Cart(object):
def __init__(self, request):
"""
Initialize the cart.
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# save an empty cart in the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart

def add(self, product, quantity=1, update_quantity=False):
"""
Add a product to the cart or update its quantity.
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': str(product.price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()

def save(self):

# update the session cart
self.session[settings.CART_SESSION_ID] = self.cart
# mark the session as "modified" to make sure it is saved
self.session.modified = True

def remove(self, product):
"""
Remove a product from the cart.
"""
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()

def __iter__(self):
"""
Iterate over the items in the cart and get the products
from the database.
"""

product_ids = self.cart.keys()
# get the product objects and add them to the cart
products = Product.objects.filter(id__in=product_ids)
for product in products:
self.cart[str(product.id)]['product'] = product
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item

def __len__(self):
"""
Count all items in the cart.
"""

return sum(item['quantity'] for item in self.cart.values())

def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in
self.cart.values())

def clear(self):

# remove cart from session
del self.session[settings.CART_SESSION_ID]
self.session.modified = True

在 cart.context_processors 之前添加我的项目名称后的新回溯:

回溯:

File "d:\virEnv\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)

File "d:\virEnv\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\virEnv\myshop\shop\views.py" in product_list
16. 'products': products})

File "d:\virEnv\lib\site-packages\django\shortcuts.py" in render
67. template_name, context, request=request, using=using)

File "d:\virEnv\lib\site-packages\django\template\loader.py" in render_to_string
97. return template.render(context, request)

File "d:\virEnv\lib\site-packages\django\template\backends\django.py" in render
95. return self.template.render(context)

File "d:\virEnv\lib\site-packages\django\template\base.py" in render
204. with context.bind_template(self):

File "c:\python35-32\Lib\contextlib.py" in __enter__
59. return next(self.gen)

File "d:\virEnv\lib\site-packages\django\template\context.py" in bind_template
256. processors = (template.engine.template_context_processors +

File "d:\virEnv\lib\site-packages\django\utils\functional.py" in __get__
33. res = instance.__dict__[self.name] = self.func(instance)

File "d:\virEnv\lib\site-packages\django\template\engine.py" in template_context_processors
105. return tuple(import_string(path) for path in context_processors)

File "d:\virEnv\lib\site-packages\django\template\engine.py" in <genexpr>
105. return tuple(import_string(path) for path in context_processors)

File "d:\virEnv\lib\site-packages\django\utils\module_loading.py" in import_string
20. module = import_module(module_path)

File "d:\virEnv\lib\importlib\__init__.py" in import_module
126. return _bootstrap._gcd_import(name[level:], package, level)

Exception Type: ImportError at /
Exception Value: No module named 'myshop.cart'

最佳答案

从屏幕截图来看,您可能将文件命名为 context_processors.py(下划线后有一个空格),而不是 context_processors.py

除此之外,在我看来,您发布的代码应该可以工作。

关于python - 导入错误位于/cart/;没有名为 'cart.context_processors' 的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37281473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com