base_models

Overview

Provides many model mixins, base templates, views and forms that are used accross all model-related kii apps (stream, particularly).

It’s a core part of kii.

Filtersets

class kii.base_models.filterset.BaseFilterSet(data=None, queryset=None, prefix=None, strict=None)[source]

A base class for more advanced FilterSets.

FilterSets are used to parse querystring from a URL and transpose it into a corresponding queryset. For example, a call on a List view with the URL /myapp/mymodel/list?status=draft would be, under the hood, converted into MyModel.objects.filter(status="draft").

Please report to django_filters documentation for in-depth explanation.

Models

Model-related features of kii are splitted accross several mixins, each implementing a single or a couple of fields. This allow us to compose our final models with great flexibility:

from kii.base_models import models

class TitleAndStatusModel(models.TitleMixin, models.StatusMixin):
    pass

class ContentAndOwnerModel(models.ContentMixin, models.OwnerMixin):
    pass

All these mixins inherit from BaseMixin, which provide useful methods and attributes.

class kii.base_models.models.BaseInheritModel(*args, **kwargs)[source]

Base class for inheriting model (see below)

class kii.base_models.models.BaseMixin(*args, **kwargs)[source]

All kii models should inherit from this one, because it provides important features.

classmethod class_name()[source]
Returns:The model class name as a string
classmethod get_template_names(suffix)[source]

base_models.views.ModelTemplateMixin uses this method to automatically discover model templates.

Considering the following model:

# myapp/models.py
from kii.base_models.models import BaseMixin

class MyModel(BaseMixin):
    pass

This method will return a list of possible templates for the given suffix, following the inheritance tree:

>>> from myapp.models import MyModel
>>> MyModel.get_template_names('detail')
['myapp/mymodel/detail.html', 'base_models/basemixin/detail.html']
>>> MyModel.get_template_names('update')
['myapp/mymodel/update.html', 'base_models/basemixin/update.html']
Returns:A list of templates name corresponding to the given suffix

(detail, list, etc.).

Will include templates from parent classes, if any

get_title()[source]
Returns:a string representing the object, for usage in templates
meta()[source]

Use this method to access model metadata in templates (underscored attributes are forbidden in django templates)

new[source]

Shortcut to check if instance is already saved or not

send(signal, instance, **kwargs)[source]

Send a model signal with self as the instance.

Other apps can then subscribe to signals in order to execute some arbitrary code at key moments:

from kii.base_models.models import StatusMixin
from kii.hook.signals import InstanceSignal

# our signal
instance_published = InstanceSignal()

# our model
class MyModel(StatusMixin):

    def mark_as_published(self, **kwargs):
        self.status = "pub"
        self.save()
        self.send(instance_published)

# our hooked function
def print_something(**kwargs):
    instance = kwargs.get('instance')
    print('Instance {0} was marked as published'.format(
        instance.pk))

# binding of our function to our signal
instance_published.connect(print_something)

If you create some model instances of the previously defined model, you would get this kind of output:

>>> from myapp.models import MyModel
>>> instance = MyModel(status="draft")
>>> instance.save()
>>> instance.mark_as_published()
Instance 1 was marked as published
Parameters:signal – a single instance as returned by

kii.hook.signals.IntanceSignal() :param instance: TODO: useless, should be deleted

class kii.base_models.models.ContentMixin(*args, **kwargs)[source]

A mixin with a content field that accepts different markup (defaults to markdown)

class kii.base_models.models.OwnerMixin(*args, **kwargs)[source]

A mixin for model instance that have an owner

owned_by(user)[source]
Returns:a boolean indicating if the instance owner

is the given user

class kii.base_models.models.StatusMixin(*args, **kwargs)[source]

A mixin with a status and a publication_date field

publication_date = None

: a datetime field which is set automatically when status is marked as pub for the first time

save(*args, **kwargs)[source]

Set publication_date to now if status is set to published

status = None

a choice field that defaults to pub

class kii.base_models.models.TimestampMixin(*args, **kwargs)[source]

A mixin with two datetime-fields that are automatically set

created = None

the creation datetime of the instance, set on the first save

last_modified = None

the last modification datetime of the instance updated on each save

class kii.base_models.models.TitleMixin(*args, **kwargs)[source]

An abstract base class for models with a title

kii.base_models.models.get_inherit_model(local_field, target, target_class, target_related_name, target_field=None)[source]

Return a model that will allow field synchronisation between an instance field and a target field The returned model will have boolean field inherit_<local_field>.

When this field is set to True on a model instance, the value of local_field will be automatically fetched from target.target_field. Inherit from must be a string pointing to a ForeignKey field on instance, with a field named target_field, from which the value will be inherited

This method will also return a dict of signals you have to register manually in order to enable field synchronization

Warning: field synchronization won’t work if you use the returned model in a abstract base class

Template tags

kii.base_models.templatetags.base_models.list_item_template(item)[source]

Find the list_item template that should render a given kii.base_models.models.BaseMixin instance

Views

class kii.base_models.views.Create(**kwargs)[source]

A generic view for creating a new instance of a model

class kii.base_models.views.Delete(**kwargs)[source]

A generic view for deleting an existing instance of a model

class kii.base_models.views.Detail(**kwargs)[source]

A generic view for detailing an existing instance of a model

class kii.base_models.views.List(**kwargs)[source]

A generic view for listing many instances of a model

filterset = None

:the filterset will be built automatically by the view from filterset_class, and used for advanced queryset filtering via GET parameters

get_filterset_kwargs()[source]
Returns:required arguments for building the filterset
get_queryset()[source]

Filter the queryset using GET parameters, if needed

class kii.base_models.views.ModelFormMixin[source]

Implements some common modelform view logic

classmethod as_view(*args, **kwargs)[source]

Deduce model from form class if needed

class kii.base_models.views.ModelTemplateMixin[source]

Implements some convenient logic for:

  • deducing the correct template to use, from model and

action - building the page title

action = None

: a string representing an action performed by the view, like update, delete, detail, list...

get_breadcrumbs()[source]

Prepend action and model label to the page title

get_template_names()[source]
Returns:an iterable of possible template names, deduced from

action and model

class kii.base_models.views.OwnerMixinCreate(**kwargs)[source]

A create view that set the newly created instance owner attribute to request.user

class kii.base_models.views.PermissionMixin[source]

A mixin that implements permission checks on single object related views.

No check will be performed if required_permission is set to None

has_required_permission(request, *args, **kwargs)[source]
Returns:A boolean indicating if the request user can access

the view

permission_denied(request)[source]
Returns:a response for the case where user has not the required

permission

required_permission = None

: a string indicating what kind of permission is required for displaying the view.

The actuel check will be done via has_required_permission().

class kii.base_models.views.RequireAuthenticationMixin[source]

Force user authentication before calling dispatch()

class kii.base_models.views.RequireOwnerMixin[source]

Permission mixin that checks the requested object is owned by request.user before granting access

class kii.base_models.views.SingleObjectPermissionMixin[source]

Implements basic pluggable permission logic on single object views

class kii.base_models.views.Update(**kwargs)[source]

A generic view for updating an existing instance of a model