ohid ohid - 5 months ago 23
Python Question

ImportError at /cart/; No module named 'cart.context_processors'

I created a context processor to set the current cart into the request context for templates by creating a new file into the cart application directory and name it

context_processors.py
:

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


I add 'cart.context_processors.cart' to the
'context_processors'
option inside the
TEMPLATES
setting of
settings.py
file. This gives me following errors:

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'


This is my cart\views.py file:

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


This is my base.html file:

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


Please advise me.

Edit:

Layout: 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


New traceback after adding my project name before cart.context_processors:

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\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'

Answer

From the screenshot, it looks as if you might have name your file context_ processors.py (with a space after the underscore) instead of context_processors.py.

Apart from that, it looks to me like the code you have posted should work.