Django Tagging¶
A generic tagging application for Django projects, which allows association of a number of tags with any Django model instance and makes retrieval of tags simple.
Installation¶
Installing an official release¶
Official releases are made available from https://pypi.python.org/pypi/django-tagging/
Source distribution¶
Download the a distribution file and unpack it. Inside is a script
named setup.py
. Enter this command:
$ python setup.py install
…and the package will install automatically.
More easily with pip:
$ pip install django-tagging
Installing the development version¶
Alternatively, if you’d like to update Django Tagging occasionally to pick
up the latest bug fixes and enhancements before they make it into an
official release, clone the git repository instead. The following
command will clone the development branch to django-tagging
directory:
git clone git@github.com:Fantomas42/django-tagging.git
Add the resulting folder to your PYTHONPATH or symlink (junction,
if you’re on Windows) the tagging
directory inside it into a
directory which is on your PYTHONPATH, such as your Python
installation’s site-packages
directory.
You can verify that the application is available on your PYTHONPATH by opening a Python interpreter and entering the following commands:
>>> import tagging
>>> tagging.__version__
0.4.dev0
When you want to update your copy of the Django Tagging source code, run
the command git pull
from within the django-tagging
directory.
Caution
The development version may contain bugs which are not present in the release version and introduce backwards-incompatible changes.
If you’re tracking git, keep an eye on the CHANGELOG before you update your copy of the source code.
Using Django Tagging in your applications¶
Once you’ve installed Django Tagging and want to use it in your Django applications, do the following:
Put
'tagging'
in yourINSTALLED_APPS
setting.Run the command
manage.py migrate
.
The migrate
command creates the necessary database tables and
creates permission objects for all installed apps that need them.
That’s it!
Settings¶
Some of the application’s behaviour can be configured by adding the appropriate settings to your project’s settings file.
The following settings are available:
MAX_TAG_LENGTH¶
Default: 50
An integer which specifies the maximum length which any tag is allowed
to have. This is used for validation in the django.contrib.admin
application and in any forms automatically generated using ModelForm
.
Registering your models¶
Your Django models can be registered with the tagging application to access some additional tagging-related features.
Note
You don’t have to register your models in order to use them with
the tagging application - many of the features added by registration
are just convenience wrappers around the tagging API provided by the
Tag
and TaggedItem
models and their managers, as documented
further below.
The register
function¶
To register a model, import the tagging.registry
module and call its
register
function, like so:
from django.db import models
from tagging.registry import register
class Widget(models.Model):
name = models.CharField(max_length=50)
register(Widget)
The following argument is required:
model
The model class to be registered.
An exception will be raised if you attempt to register the same class more than once.
The following arguments are optional, with some recommended defaults - take care to specify different attribute names if the defaults clash with your model class’ definition:
tag_descriptor_attr
The name of an attribute in the model class which will hold a tag descriptor for the model. Default:
'tags'
See TagDescriptor below for details about the use of this descriptor.
tagged_item_manager_attr
The name of an attribute in the model class which will hold a custom manager for accessing tagged items for the model. Default:
'tagged'
.See ModelTaggedItemManager below for details about the use of this manager.
TagDescriptor
¶
When accessed through the model class itself, this descriptor will return
a ModelTagManager
for the model. See ModelTagManager below for
more details about its use.
When accessed through a model instance, this descriptor provides a handy means of retrieving, updating and deleting the instance’s tags. For example:
>>> widget = Widget.objects.create(name='Testing descriptor')
>>> widget.tags
[]
>>> widget.tags = 'toast, melted cheese, butter'
>>> widget.tags
[<Tag: butter>, <Tag: melted cheese>, <Tag: toast>]
>>> del widget.tags
>>> widget.tags
[]
ModelTagManager
¶
A manager for retrieving tags used by a particular model.
Defines the following methods:
get_queryset()
– as this method is redefined, anyQuerySets
created by this model will be initially restricted to contain the distinct tags used by all the model’s instances.cloud(*args, **kwargs)
– creates a list of tags used by the model’s instances, withcount
andfont_size
attributes set for use in displaying a tag cloud.See the documentation on
Tag
’s manager’s cloud_for_model method for information on additional arguments which can be given.related(self, tags, *args, **kwargs)
– creates a list of tags used by the model’s instances, which are also used by all instance which have the giventags
.See the documentation on
Tag
’s manager’s related_for_model method for information on additional arguments which can be given.usage(self, *args, **kwargs))
– creates a list of tags used by the model’s instances, with optional usages counts, restriction based on usage counts and restriction of the model instances from which usage and counts are determined.See the documentation on
Tag
’s manager’s usage_for_model method for information on additional arguments which can be given.
Example usage:
# Create a ``QuerySet`` of tags used by Widget instances
Widget.tags.all()
# Retrieve a list of tags used by Widget instances with usage counts
Widget.tags.usage(counts=True)
# Retrieve tags used by instances of WIdget which are also tagged with
# 'cheese' and 'toast'
Widget.tags.related(['cheese', 'toast'], counts=True, min_count=3)
ModelTaggedItemManager
¶
A manager for retrieving model instance for a particular model, based on their tags.
related_to(obj, queryset=None, num=None)
– creates a list of model instances which are related toobj
, based on its tags. If aqueryset
argument is provided, it will be used to restrict the resulting list of model instances.If
num
is given, a maximum ofnum
instances will be returned.with_all(tags, queryset=None)
– creates aQuerySet
containing model instances which are tagged with all the given tags. If aqueryset
argument is provided, it will be used as the basis for the resultingQuerySet
.with_any(tags, queryset=None)
– creates aQuerySet
containing model instances which are tagged with any the given tags. If aqueryset
argument is provided, it will be used as the basis for the resultingQuerySet
.
Tagged items¶
The relationship between a Tag
and an object is represented by
the TaggedItem
model, which lives in the tagging.models
module.
API reference¶
Fields¶
TaggedItem
objects have the following fields:
tag
– TheTag
an object is associated with.content_type
– TheContentType
of the associated model instance.object_id
– The id of the associated object.object
– The associated object itself, accessible via the Generic Relations API.
Manager functions¶
The TaggedItem
model has a custom manager which has the following
helper methods, which accept either a QuerySet
or a Model
class as one of their arguments. To restrict the objects which are
returned, pass in a filtered QuerySet
for this argument:
get_by_model(queryset_or_model, tag)
– creates aQuerySet
containing instances of the specififed model which are tagged with the given tag or tags.get_intersection_by_model(queryset_or_model, tags)
– creates aQuerySet
containing instances of the specified model which are tagged with every tag in a list of tags.get_by_model
will call this function behind the scenes when you pass it a list, so you can useget_by_model
instead of calling this method directly.get_union_by_model(queryset_or_model, tags)
– creates aQuerySet
containing instances of the specified model which are tagged with any tag in a list of tags.
Basic usage¶
Retrieving tagged objects¶
Objects may be retrieved based on their tags using the get_by_model
manager method:
>>> from shop.apps.products.models import Widget
>>> from tagging.models import Tag
>>> house_tag = Tag.objects.get(name='house')
>>> TaggedItem.objects.get_by_model(Widget, house_tag)
[<Widget: pk=1>, <Widget: pk=2>]
Passing a list of tags to get_by_model
returns an intersection of
objects which have those tags, i.e. tag1 AND tag2 … AND tagN:
>>> thing_tag = Tag.objects.get(name='thing')
>>> TaggedItem.objects.get_by_model(Widget, [house_tag, thing_tag])
[<Widget: pk=1>]
Functions which take tags are flexible when it comes to tag input:
>>> TaggedItem.objects.get_by_model(Widget, Tag.objects.filter(name__in=['house', 'thing']))
[<Widget: pk=1>]
>>> TaggedItem.objects.get_by_model(Widget, 'house thing')
[<Widget: pk=1>]
>>> TaggedItem.objects.get_by_model(Widget, ['house', 'thing'])
[<Widget: pk=1>]
Restricting objects returned¶
Pass in a QuerySet
to restrict the objects returned:
# Retrieve all Widgets which have a price less than 50, tagged with 'house'
TaggedItem.objects.get_by_model(Widget.objects.filter(price__lt=50), 'house')
# Retrieve all Widgets which have a name starting with 'a', tagged with any
# of 'house', 'garden' or 'water'.
TaggedItem.objects.get_union_by_model(Widget.objects.filter(name__startswith='a'),
['house', 'garden', 'water'])
Utilities¶
Tag-related utility functions are defined in the tagging.utils
module:
parse_tag_input(input)
¶
Parses tag input, with multiple word input being activated and delineated by commas and double quotes. Quotes take precedence, so they may contain commas.
Returns a sorted list of unique tag names.
See tag input for more details.
Model Fields¶
The tagging.fields
module contains fields which make it easy to
integrate tagging into your models and into the
django.contrib.admin
application.
Field types¶
TagField
¶
A CharField
that actually works as a relationship to tags “under
the hood”.
Using this example model:
class Link(models.Model):
...
tags = TagField()
Setting tags:
>>> l = Link.objects.get(...)
>>> l.tags = 'tag1 tag2 tag3'
Getting tags for an instance:
>>> l.tags
'tag1 tag2 tag3'
Getting tags for a model - i.e. all tags used by all instances of the model:
>>> Link.tags
'tag1 tag2 tag3 tag4 tag5'
This field will also validate that it has been given a valid list of tag names, separated by a single comma, a single space or a comma followed by a space.
Form fields¶
The tagging.forms
module contains a Field
for use with
Django’s forms library which takes care of validating tag name
input when used in your forms.
Field types¶
TagField
¶
A form Field
which is displayed as a single-line text input, which
validates that the input it receives is a valid list of tag names.
When you generate a form for one of your models automatically, using
the ModelForm
class, any tagging.fields.TagField
fields in your
model will automatically be represented by a tagging.forms.TagField
in the generated form.
Generic views¶
The tagging.views
module contains views to handle simple cases of
common display logic related to tagging.
tagging.views.TaggedObjectList
¶
Description:
A view that displays a list of objects for a given model which have a
given tag. This is a thin wrapper around the
django.views.generic.list.ListView
view, which takes a
model and a tag as its arguments (in addition to the other optional
arguments supported by ListView
), building the appropriate
QuerySet
for you instead of expecting one to be passed in.
Required arguments:
tag
: The tag which objects of the given model must have in order to be listed.
Optional arguments:
Please refer to the ListView documentation for additional optional arguments which may be given.
related_tags
: IfTrue
, arelated_tags
context variable will also contain tags related to the given tag for the given model.
related_tag_counts
: IfTrue
andrelated_tags
isTrue
, each related tag will have acount
attribute indicating the number of items which have it in addition to the given tag.
Template context:
Please refer to the ListView documentation for additional template context variables which may be provided.
tag
: TheTag
instance for the given tag.
Example usage¶
The following sample URLconf demonstrates using this generic view to list items of a particular model class which have a given tag:
from django.conf.urls.defaults import *
from tagging.views import TaggedObjectList
from shop.apps.products.models import Widget
urlpatterns = patterns('',
url(r'(?u)^widgets/tag/(?P<tag>[^/]+)/$',
TaggedObjectList.as_view(model=Widget, paginate_by=10, allow_empty=True),
name='widget_tag_detail'),
)
The following sample view demonstrates wrapping this generic view to perform filtering of the objects which are listed:
from myapp.models import People
from tagging.views import TaggedObjectList
class TaggedPeopleFilteredList(TaggedObjectList):
queryset = People.objects.filter(country__code=country_code)