From 30c39263a50149fb86c2bb4aa6f4b3caf80accf7 Mon Sep 17 00:00:00 2001 From: Lazybird Date: Sun, 23 Mar 2014 19:54:59 +0100 Subject: [PATCH] Added support for custom lookup parameters. Issue #12. --- carton/cart.py | 15 ++++++++++++++- carton/tests/tests.py | 18 +++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/carton/cart.py b/carton/cart.py index 762f3ae..e06ece0 100644 --- a/carton/cart.py +++ b/carton/cart.py @@ -1,5 +1,7 @@ from decimal import Decimal +from django.conf import settings + from carton import module_loading from carton import settings as carton_settings @@ -61,9 +63,20 @@ def __contains__(self, product): def get_product_model(self): return module_loading.get_product_model() + def filter_products(self, queryset): + """ + Applies lookup parameters defined in settings. + """ + lookup_parameters = getattr(settings, 'CART_PRODUCT_LOOKUP', None) + if lookup_parameters: + queryset = queryset.filter(**lookup_parameters) + return queryset + def get_queryset(self): product_model = self.get_product_model() - return product_model._default_manager.all() + queryset = product_model._default_manager.all() + queryset = self.filter_products(queryset) + return queryset def update_session(self): """ diff --git a/carton/tests/tests.py b/carton/tests/tests.py index 89308ee..6895911 100644 --- a/carton/tests/tests.py +++ b/carton/tests/tests.py @@ -1,8 +1,12 @@ from django.core.urlresolvers import reverse from django.test import TestCase - from carton.tests.models import Product +try: + from django.test import override_settings +except ImportError: + from django.test.utils import override_settings + class CartTests(TestCase): @@ -99,3 +103,15 @@ def test_cart_items_are_cleared(self): response = self.client.get(self.url_show) self.assertNotContains(response, 'deer') self.assertNotContains(response, 'moose') + + @override_settings(CART_PRODUCT_LOOKUP={'price__gt': 1}) + def test_custom_product_filter_are_applied(self): + # We modify the queryset to exclude some products. For these excluded + # we should not be able to add them in the cart. + exclude = Product.objects.create(name='EXCLUDE', price=0.99, custom_id=100) + exclude_data = {'product_id': exclude.pk} + self.client.post(self.url_add, self.deer_data) + self.client.post(self.url_add, exclude_data) + response = self.client.get(self.url_show) + self.assertNotContains(response, 'EXCLUDE') + self.assertContains(response, 'deer')