2016-05-17 89 views
1

我創建了一個上下文處理器通過創建一個新的文件到購物車應用程序目錄設置當前車成模板的請求上下文並將其命名爲context_processors.pyImportError at/cart /;沒有名爲模塊「cart.context_processors」

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

我添加'cart.context_processors.cart'設置爲TEMPLATES設置的settings.py文件中的'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' 

這是我的車\ 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

cart.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' 
+1

你可以顯示你的項目的佈局,特別是'購物車'應用程序。 – Alasdair

+0

我添加了包含購物車應用的總佈局。請參閱圖片 – ohid

+0

仍然不起作用 – ohid

回答

1

從截圖,它看起來好像你可能有,而不是context_processors.py名的文件context_ processors.py(帶下劃線後有一個空格)。

除此之外,它看起來像我已經發布的代碼應該工作。

+0

是的,你的建議工作。謝謝 – ohid

0

更換cart.context_processors.cartyour_project_name.cart.context_processors.cart

+0

根據您的建議,我添加了我的項目名稱,但仍然無法使用。我添加了新的追溯。請參閱我的編輯部分。 – ohid

相關問題