Skip to main content

Django Cart.

Project description

Build status Code health Python versions PyPI downloads Software license Project Status

Django Cart.

Installation

Install with pip:

$ pip install django-ok-cart

Update INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'ok_cart',
    ...
]

Apply migrations:

python manage.py migrate

Available settings

CART_ADD_PIPELINES - Functions to run after adding each passed item to the cart.

# settings.py

CART_ADD_PIPELINES = (
   'apps.store.contrib.cart.pipelines.save_shop_id_to_cart_parameters',
)

# apps.store.contrib.cart.pipelines.py

def save_shop_id_to_cart_parameters(
        cart: 'Cart',
        user: 'User',
        content_object: 'Model',
        cart_item: 'CartItem',
        cart_group: 'CartGroup',
        **kwargs
):
    if isinstance(content_object, Product) and cart_group:
        cart_group.parameters['shop_id'] = content_object.shop_id
        cart_group.save(update_fields=['parameters'])
        cart_item.parameters['shop_id'] = content_object.shop_id
        cart_item.save(update_fields=['parameters'])

CART_POST_ADD_PIPELINES - Functions to run after adding all passed items to the cart.

Note: To save cart items prices you need to implement your custom pipeline like in example below.

# settings.py

CART_POST_ADD_PIPELINES = (
   'apps.store.contrib.cart.pipelines.apply_product_prices_to_cart',
)

# apps.store.contrib.cart.pipelines.py

from ok_cart.selectors import get_cart_items_by_cart
from apps.store.models import Product
from apps.store.selectors import get_product_price
from shared.utils import get_content_type

def get_product_cart_items(
        *,
        cart: 'Cart',
        with_related: bool = True
) -> 'QuerySet':
    cart_items = (
        get_cart_items_by_cart(
            cart=cart,
            with_related=with_related
        )
        .filter(
            content_type=get_content_type(Product)
        )
    )

    return cart_items

def get_cart_item_price(
    *,
    content_object: 'Model',
    user: 'User',
    cart: 'Cart',
    **kwargs
) -> Decimal:
    """
    Return price for specific type of object
    """
    price = None

    if isinstance(content_object, Product):
        price = get_product_price(product=content_object)

    return price

def apply_product_prices_to_cart(
    *,
    cart: 'Cart',
    user: 'User',
    **kwargs
):
    cart_items = (
        get_product_cart_items(
            cart=cart,
            with_related=False
        )
    )

    for cart_item in cart_items:
        price = (
            get_cart_item_price(
                content_object=cart_item.content_object,
                user=user,
                cart=cart,
            )
        )
        cart_item.price = price
        cart_item.save()

CART_ELEMENT_REPRESENTATION_SERIALIZERS - Serializers to represent cart items objects.

# settings.py

CART_ELEMENT_REPRESENTATION_SERIALIZERS = {
    'store.Product': 'api.rest.store.serializers.product.retrieve.ProductCartRetrieveSerializer',
}

CART_ELEMENT_ALLOWED_TYPES - Tuple of tuples of cart items allowed types.

# settings.py

CART_ELEMENT_ALLOWED_TYPES = (
    ('store', 'product'),
)

CART_PRICE_PROCESSOR - Function to modify cart prices, like converting to another currency.

# settings.py

CART_PRICE_PROCESSOR = 'apps.store.contrib.cart.cart_price_processor'

# apps.store.contrib.cart.price.py

def cart_price_processor(
        *,
        request,
        price
):
    return price

CART_BASE_API_VIEW - Base API View for your cart views.

# settings.py

CART_BASE_API_VIEW = 'apps.store.contrib.cart.StandardsMixin'

CART_GETTER - Function to get or create cart. ok_cart.selectors.get_cart_from_request by default.

# settings.py

CART_GETTER = 'apps.store.contrib.cart.selectors.cart_getter'

# store.contrib.cart.selectors.py

def cart_getter(
        *,
        request: 'HttpRequest',
        cart_queryset: 'QuerySet' = Cart.objects.open().optimized(),
        auto_create: bool = True
) -> 'Cart':
    pass

Quickstart

To enable cart views, add next URL patterns:

urlpatterns = [
    ...
    path('', include('ok_cart.api.urls')),
]

Endpoints

  1. /api/v1/cart/change/ - API View to add items to cart. type value is a structure like app_label.model_name.

Possible payload:

[
    {
        "element": {
            "id": "9619f790-9a02-4ac3-ad34-22e4da3a6d54",
            "type": "store.product"
        },
        "quantity": 1
    }
]
  1. /api/v1/cart/clear/ - API View to remove all items from cart.

  2. /api/v1/cart/quantity/ - API View to get cart’s quantity and total price.

Possible result:

{
    "quantity": 3,
    "total_price": 750
}
  1. /api/v1/cart/retrieve/ - API View to retrieve cart data.

Possible result:

{
    "groups": [
        {
            "id": 34,
            "price": 750,
            "base": {
                "element": {
                    "id": "9619f790-9a02-4ac3-ad34-22e4da3a6d54",
                    "caption": "Ноутбук",
                    "type": "store.product",
                    "props": {
                        "title": "Ноутбук",
                        "short_description": "Ноут для чайников",
                        "category": {
                            "id": 1,
                            "caption": "Ноутбуки и компьютеры",
                            "type": "store.category",
                            "props": {
                                "id": 1,
                                "label": "noutbuk-komp",
                                "title": "Ноутбуки и компьютеры",
                                "parent": null,
                                "depth": 0
                            }
                        },
                        "image": {},
                        "shop": null,
                        "shop_identifier": "",
                        "price": 250,
                        "old_price": null,
                        "url": "/product/noutbuk-0c4qoewu-vxmong1s/"
                    }
                },
                "quantity": 3,
                "price": 250,
                "parameters": {
                    "shop_id": null
                }
            },
            "relations": [],
            "parameters": {
                "shop_id": null
            }
        }
    ],
    "quantity": 3,
    "total_price": 750,
    "parameters": {}
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-ok-cart-0.0.1.tar.gz (14.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_ok_cart-0.0.1-py3-none-any.whl (19.4 kB view details)

Uploaded Python 3

File details

Details for the file django-ok-cart-0.0.1.tar.gz.

File metadata

  • Download URL: django-ok-cart-0.0.1.tar.gz
  • Upload date:
  • Size: 14.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/49.2.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.9.2

File hashes

Hashes for django-ok-cart-0.0.1.tar.gz
Algorithm Hash digest
SHA256 3dc3f27f7f6619aff96f062181a85819cc81f9f18ded69a1f2d581a0aaee721d
MD5 9484acb18d58ab0a2f9aae3029c299d4
BLAKE2b-256 4cbac635e6f0cdcaea44d72e1476f5e55207fd68dd7fb0120818d443c0665782

See more details on using hashes here.

File details

Details for the file django_ok_cart-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: django_ok_cart-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 19.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/49.2.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.9.2

File hashes

Hashes for django_ok_cart-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6fc7bf4f5bc9d97b0422f70257b428e1a911dcb8d77849f99cf5f9fd9ba18e79
MD5 a0402d53cf0a61ae79d99a5857dc954b
BLAKE2b-256 507925e8e335d6fa0f86ad337ede09d9bad33acde4d2fdf55863dfa4cec67a7a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page