How to add own criteria¶
In this how-to you will learn how to add own criteria to LFS.
The goal in this how-to is to create a criterion, for which the shop manager can enter a SKU and decide (via operators) whether the criterion is valid if the product with the entered SKU is within the cart or not.
download the example application here.
Create an application¶
Implement the Criterion Model¶
The main part of the application consists of a criterion model which must
inherit from the
Criterion base class.
Create the Class¶
class ProductCriterion(Criterion): value = models.CharField(max_length=100)
The only attribute we need is the value the shop manager will save for the criterion. The attribute can have any type you need. In this example we use a simple character field. The entered SKU is checked within the products in the cart. Dependent on the chosen operator the criteria is valid if the product is within the cart or not.
Implement necessary Methods¶
In the next steps we implement all necessary methods which are needed to make
the criterion work. In this case these are
get_operators method needs to return the available operators for this
criterion. It is a list of list, whereas the first value is an integer and the
second value is the name of the operator.
def get_operators(self): return [ [0, _(u"Is in cart")], [1, _(u"Is not in cart")], ]
is_valid method needs to return a boolean. If it returns
criterion is considered valid, it returns
False the criterion is considered
def is_valid(self): if self.product: return self.value == self.product.sku elif self.cart: result = any([self.value == item.product.sku for item in self.cart.get_items()]) return result if self.operator == 0 else not result else: return False
is_valid method (as in all methods of the
class) following attributes are available:
- This is only set, when the criterion is called from the product detail view otherwise it is
- The current cart of the current user.
- The current request.
Plug in the Criterion¶
Now as the code is ready, you can easily plugin your own criterion:
Add your application to the PYTHONPATH
Add your application to settings.INSTALLED_APPS and sync your database:
INSTALLED_APPS = ( ... "product_criterion", )
Add the class to the LFS_CRITERIA setting:
LFS_CRITERIA = [ ... ["product_criterion.models.ProductCriterion", _(u"Product Criterion")], ]
As all criteria are models, you have to synchronize your database:
$ bin/django syncdb
Restart your instance and the criterion should be available for selection, for instance within the discount criteria tab.
And that’s it¶
You should now see your criterion within the criteria tab of
instance. You can enter a product SKU to it and select one of the above