Setting the cart into the request context

Let's create a context processor to set the current cart into the request context. We will be able to access the cart in any template.

Create a new file inside the cart application directory and name it context_processors.py. Context processors can reside anywhere in your code, but creating them here will keep your code well organized. Add the following code to the file:

from .cart import Cart

def cart(request):
return {'cart': Cart(request)}

A context processor is a function that receives the request object as a parameter and returns a dictionary of objects that will be available to all the templates rendered using RequestContext. In our context processor, we instantiate the cart using the request object and make it available for the templates as a variable named cart.

Edit the settings.py file of your project and add cart.context_processors.cart to the context_processors option inside the TEMPLATES setting as follows:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# ...
'cart.context_processors.cart',
],
},
},
]

The cart context processor will be executed every time a template is rendered using Django's RequestContext. The cart variable will be set in the context of your templates.

Context processors are executed in all the requests that use RequestContext. You might want to create a custom template tag instead of a context processor if your functionality is not needed in all templates, especially if it involves database queries.

Now, edit the shop/base.html template of the shop application and find the following lines:

<div class="cart">
Your cart is empty.
</div>

Replace the previous lines with the following code:

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

Reload your server using the command python manage.py runserver. Open http://127.0.0.1:8000/ in your browser and add some products to the cart.
In the header of the website, you can see the total number of items in the cart and the total cost, as follows:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset