aboutsummaryrefslogtreecommitdiff
path: root/tagging/registry.py
blob: 30c00ae7a6b705579fe072f7456bb35e66ddf9bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Registery for tagging.
"""
from tagging.managers import TagDescriptor
from tagging.managers import ModelTaggedItemManager

registry = []


class AlreadyRegistered(Exception):
    """
    An attempt was made to register a model more than once.
    """
    pass


def register(model, tag_descriptor_attr='tags',
             tagged_item_manager_attr='tagged'):
    """
    Sets the given model class up for working with tags.
    """
    if model in registry:
        raise AlreadyRegistered(
            "The model '%s' has already been registered." %
            model._meta.object_name)
    if hasattr(model, tag_descriptor_attr):
        raise AttributeError(
            "'%s' already has an attribute '%s'. You must "
            "provide a custom tag_descriptor_attr to register." % (
                model._meta.object_name,
                tag_descriptor_attr,
            )
        )
    if hasattr(model, tagged_item_manager_attr):
        raise AttributeError(
            "'%s' already has an attribute '%s'. You must "
            "provide a custom tagged_item_manager_attr to register." % (
                model._meta.object_name,
                tagged_item_manager_attr,
            )
        )

    # Add tag descriptor
    setattr(model, tag_descriptor_attr, TagDescriptor())

    # Add custom manager
    ModelTaggedItemManager().contribute_to_class(
        model, tagged_item_manager_attr)

    # Finally register in registry
    registry.append(model)