/ error /中的ImportError;没有名为'cart.context_processors'的模块

时间:2016-05-17 16:14:49

标签: python django

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

context_processors.py

我将'cart.context_processors.cart'添加到from .cart import Cart def cart(request): return {'cart': Cart(request)} 文件的'context_processors'设置中的TEMPLATES选项中。这给了我以下错误:

settings.py

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

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'

这是我的base.html文件:

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})

请告诉我。

修改:

布局:enter image description here

cart.py:

{% 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>

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

回溯:

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

2 个答案:

答案 0 :(得分:1)

从屏幕截图中,您可能会将文件命名为context_ processors.py(在下划线后面加一个空格),而不是context_processors.py

除此之外,我认为您发布的代码应该可以正常工作。

答案 1 :(得分:0)

cart.context_processors.cart替换为your_project_name.cart.context_processors.cart