Python API

Models

class lorikeet.models.Cart(*args, **kwargs)[source]

An in-progress shopping cart.

Carts are associated with the user for an authenticated request, or with the session otherwise; in either case it can be accessed on request.cart.

delivery_address_subclass

Get the delivery address instance selected for this cart.

Returns an instance of one of the registered DeliveryAddress subclasses.

get_grand_total()[source]

Calculate the grand total for this cart.

is_complete(raise_exc=False, for_checkout=False)[source]

Determine if this cart is able to be checked out.

If this function returns False, the .errors attribute will be set to a IncompleteCartErrorSet containing all of the reasons the cart cannot be checked out.

Parameters:raise_exc (bool) – If True and there are errors, raise the resulting IncompleteCartErrorSet instead of just returning False.
Returns:Whether this cart can be checked out.
Return type:bool
payment_method_subclass

Get the payment method instance selected for this cart.

Returns an instance of one of the registered PaymentMethod subclasses.

class lorikeet.models.LineItem(*args, **kwargs)[source]

An individual item that is either in a shopping cart or on an order.

This model doesn’t do anything by itself; you’ll need to subclass it as described in the Getting Started Guide.

check_complete(for_checkout=False)[source]

Checks that this line item is ready to be checked out.

This method should raise IncompleteCartError if the line item is not ready to be checked out (e.g. there is insufficient stock in inventory to fulfil this line item). By default it does nothing.

Parameters:for_checkout (bool) – Set to True when the cart is about to be checked out. See the documentation for prepare_for_checkout() for more details. is going to be called within the current transaction, so you should use things like select_for_update.
get_total()[source]

Returns the total amount to charge on this LineItem.

By default this raises NotImplemented; subclasses of this class need to override this.

If you want to know the total for this line item from your own code, use the total() property rather than calling this function.

prepare_for_checkout()[source]

Prepare this line item for checkout.

This is called in the checkout process, shortly before the payment method is charged, within a database transaction that will be rolled back if payment is unsuccessful.

This function shouldn’t fail. (If it does, the transaction will be rolled back and the payment won’t be processed so nothing disastrous will happen, but the user will get a 500 error which you probably don’t want.)

The check_complete() method is guaranteed to be called shortly before this method, within the same transaction, and with the for_checkout parameter set to True. Any checks you need to perform to ensure checkout will succeed should be performed there, and when for_checkout is true there you should ensure that those checks remain valid for the remainder of the database transaction (e.g. using select_for_update).

total

The total cost for this line item.

Returns the total actually charged to the customer if this item is attached to an Order, or calls get_total() otherwise.

class lorikeet.models.DeliveryAddress(*args, **kwargs)[source]

An address that an order can be delivered to.

This model doesn’t do anything by itself; you’ll need to subclass it as described in the Getting Started Guide.

class lorikeet.models.PaymentMethod(*args, **kwargs)[source]

A payment method, like a credit card or bank details.

This model doesn’t do anything by itself; you’ll need to subclass it as described in the Getting Started Guide.

class lorikeet.models.Order(*args, **kwargs)[source]

A completed, paid order.

delivery_address_subclass

Get the delivery address instance selected for this cart.

Returns an instance of one of the registered DeliveryAddress subclasses.

get_absolute_url(token=False)[source]

Get the absolute URL of an order details view.

Parameters:token (bool) – If true, include in the URL a token that allows unauthenticated access to the detail view.

See the documentation for the LORIKEET_ORDER_DETAIL_VIEW setting.

invoice_id

The ID of the invoice.

If custom_invoice_id is set, it will be returned. Otherwise, the PK of the order object will be returned.

payment_method_subclass

Get the delivery address instance selected for this cart.

Returns an instance of one of the registered DeliveryAddress subclasses.

payment_subclass

Get the payment method instance selected for this cart.

Returns an instance of one of the registered PaymentMethod subclasses.

Serializers

lorikeet.api_serializers.registry

Registers serializers with their associated models.

This is used instead of discovery or a metaclass-based registry as making sure the classes to be registered actually get imported can be fragile and non-obvious to debug.

The registry instance is available at lorikeet.api_serializers.registry.

registry.register(model, serializer)

Associate model with serializer.

class lorikeet.api_serializers.PrimaryKeyModelSerializer(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)[source]

A serializer that accepts the primary key of an object as input.

When read from, this serializer works exactly the same as ModelSerializer. When written to, it accepts a valid primary key of an existing instance of the same model. It can’t be used to add or edit model instances.

This is provided as a convenience, for the common use case of a LineItem subclass that has a foreign key to a product model; see the Getting Started Guide for a usage example.

get_queryset()[source]

Returns a queryset which the model instance is retrieved from.

By default, returns self.Meta.model.objects.all().

class lorikeet.api_serializers.LineItemSerializer(instance=None, *args, **kwargs)[source]

Base serializer for LineItem subclasses.

Mixins

Template Tags

lorikeet.templatetags.lorikeet.lorikeet_cart(context)[source]

Returns the current state of the user’s cart.

Returns a JSON string of the same shape as a response from GET /_cart/. Requires that the current request be in the template’s context.

Cart Checkers

lorikeet.cart_checkers.delivery_address_required(cart)[source]

Prevents checkout unless a delivery address is selected.

lorikeet.cart_checkers.payment_method_required(cart)[source]

Prevents checkout unless a payment method is selected.

lorikeet.cart_checkers.cart_not_empty(cart)[source]

Prevents checkout of an empty cart.

lorikeet.cart_checkers.email_address_if_anonymous(cart)[source]

Prevents anonymous users checking out without an email address.

Exceptions

class lorikeet.exceptions.PaymentError(info=None)[source]

Represents an error accepting payment on a PaymentMethod.

Parameters:info – A JSON-serializable object containing details of the problem, to be passed to the client.
class lorikeet.exceptions.IncompleteCartError(code, message, field=None)[source]

Represents a reason that a cart is not ready for checkout.

Similar to a Django ValidationError, but not used to reject a change based on submitted data.

Parameters:
  • code (str) – A consistent, non-localised string to identify the specific error.
  • message (str) – A human-readable message that explains the error.
  • field (str, NoneType) – The field that the error relates to. This should match one of the fields in the cart’s serialized representation, or be set to None if a specific field does not apply.
to_json()[source]

Returns the error in a JSON-serializable form.

Return type:dict
class lorikeet.exceptions.IncompleteCartErrorSet(errors=())[source]

Represents a set of multiple reasons a cart is not ready for checkout.

You can raise this exception instead of IncompleteCartError if you would like to provide multiple errors at once.

This class is iterable.

Parameters:errors (Iterable[IncompleteCartError]) – All of the errors that apply.
add(error)[source]

Add a new error to the set.

Parameters:error (IncompleteCartError, IncompleteCartErrorSet) – The error to add. If an IncompleteCartErrorSet instance is passed, it will be merged into this one.
to_json()[source]

Returns the list of errors in a JSON-serializable form.

Return type:dict

Settings

Lorikeet’s behaviour can be altered by setting the following settings in your project’s settings.py file.

LORIKEET_CART_COMPLETE_CHECKERS

Default value:

[
    'lorikeet.cart_checkers.delivery_address_required',
    'lorikeet.cart_checkers.payment_method_required',
    'lorikeet.cart_checkers.cart_not_empty',
    'lorikeet.cart_checkers.email_address_if_anonymous',
]

Checkers that validate whether or not a cart is ready for checkout. For more detail on these, including how to write your own, refer to the guide on Cart Checkers.

Warning

The default value for LORIKEET_CART_COMPLETE_CHECKERS contains important built-in checkers that you probably don’t want to disable, because they prevent things like going through checkout with an empty cart. If you override this setting, make sure you include them!

LORIKEET_ORDER_DETAIL_VIEW

Default value: None

The name of a URL pattern that points to a view describing a single Order object. The regex for this URL pattern must have an id kwarg that matches the numeric ID of the order object; custom invoice IDs in URLs are not yet supported.

This value should be the same as the string you’d pass as the first argument to django.core.urlresolvers.reverse(), e.g. 'products:order'.

If set, it will be used in lorikeet.models.Order.get_absolute_url() and POST /_cart/checkout/.

LORIKEET_SET_CSRFTOKEN_EVERYWHERE

Default value: True

The Lorikeet JavaScript library expects the CSRF token cookie to be set, but it isn’t always (see the warning in the Django CSRF docs). For convenience, Lorikeet tells Django to set the cookie on every request (the equivalent of calling ensure_csrf_cookie() on every request). If you wish to handle this yourself, you can set this setting to False to disable this behaviour.

LORIKEET_INVOICE_ID_GENERATOR

Default value: None

Todo

Document this here as well as in recipes

Signals

lorikeet.signals.order_checked_out

Fired when a cart is checked out and an order is generated.

Parameters:

  • order - the Order instance that was just created.

Signal handlers can return a dictionary, which will be merged into the response returned to the client when the checkout happens. They can also return None, but should not return anything else.

If signals raise an exception, the exception will be logged at the warning severity level; it’s up to you to be able to report this and respond appropriately.

Note

This signal is fired synchronously during the checkout process, before the checkout success response is returned to the client. If you don’t need to return data to the client, try to avoid doing any long-running or failure-prone processes inside handlers for this signal.

For example, if you need to send order details to a fulfilment provider, you could use a signal handler to enqueue a task in something like Celery, or you could have a model with a one-to-one foreign key which you create in a batch process.