Commits

Ian George committed d808714

initial commit

  • Participants

Comments (0)

Files changed (38)

+.pyc$
+.svn
+.orig
+^parts/
+^bin/
+^build/
+^include/
+^lib/
+^src/
+^develop-eggs/
+^downloads/
+^eggs/
+^parts/
+^.installed.cfg
+db$
+^media/cache/
+^media/medialibrary/
+^static_serve/
+^website/quiet
+^front_end_build/
+^log/
+^logs/
+^www/

File CHANGELOG.txt

+========================
+Django Tagging Changelog
+========================
+
+SVN Trunk Changes:
+-------------------
+
+Version 0.3.0, 22nd August 2009:
+--------------------------------
+
+* Fixes for Django 1.0 compatibility.
+
+* Added a ``tagging.generic`` module for working with list of objects
+  which have generic relations, containing a ``fetch_content_objects``
+  function for retrieving content objects for a list of ``TaggedItem``s
+  using ``number_of_content_types + 1`` queries rather than the
+  ``number_of_tagged_items * 2`` queries you'd get by iterating over the
+  list and accessing each item's ``object`` attribute.
+
+* Added a ``usage`` method to ``ModelTagManager``.
+
+* ``TaggedItemManager``'s methods now accept a ``QuerySet`` or a
+  ``Model`` class. If a ``QuerySet`` is given, it will be used as the
+  basis for the ``QuerySet``s the methods return, so can be used to
+  restrict results to a subset of a model's instances. The 
+  `tagged_object_list`` generic view and ModelTaggedItemManager``
+  manager have been updated accordingly.
+
+* Removed ``tagging\tests\runtests.py``, as tests can be run with
+  ``django-admin.py test --settings=tagging.tests.settings``.
+
+* A ``tagging.TagDescriptor`` is now added to models when registered.
+  This returns a ``tagging.managers.ModelTagManager`` when accessed on a
+  model class, and provide access to and control over tags when used on
+  an instance.
+
+* Added ``tagging.register`` to register models with the tagging app.
+  Initially, a ``tagging.managers.ModelTaggedItemManager`` is added for
+  convenient access to tagged items.
+
+* Moved ``TagManager`` and ``TaggedItemManager`` to ``models.py`` - gets
+  rid of some import related silliness, as ``TagManager`` needs access
+  to ``TaggedItem``.
+
+Version 0.2.1, 16th Jan 2008:
+-----------------------------
+
+* Fixed a bug with space-delimited tag input handling - duplicates
+  weren't being removed and the list of tag names wasn't sorted.
+
+Version 0.2, 12th Jan 2008:
+---------------------------
+
+Packaged from revision 122 in Subversion; download at
+http://django-tagging.googlecode.com/files/tagging-0.2.zip
+
+* Added a ``tag_cloud_for_model`` template tag.
+
+* Added a ``MAX_TAG_LENGTH`` setting.
+
+* Multi-word tags are here - simple space-delimited input still works.
+  Double quotes and/or commas are used to delineate multi- word tags.
+  As far as valid tag contents - anything goes, at least initially.
+
+* BACKWARDS-INCOMPATIBLE CHANGE - ``django.utils.get_tag_name_list`` and
+  related regular expressions have been removed in favour of a new tag
+  input parsing function, ``django.utils.parse_tag_input``.
+
+* BACKWARDS-INCOMPATIBLE CHANGE - ``Tag`` and ``TaggedItem`` no longer
+  declare an explicit ``db_table``. If you can't rename your tables,
+  you'll have to put these back in manually.
+
+* Fixed a bug in calculation of logarithmic tag clouds - ``font_size``
+  attributes were not being set in some cases when the least used tag in
+  the cloud had been used more than once.
+
+* For consistency of return type, ``TaggedItemManager.get_by_model`` now
+  returns an empty ``QuerySet`` instead of an empty ``list`` if
+  non-existent tags were given.
+
+* Fixed a bug caused by ``cloud_for_model`` not passing its
+  ``distribution`` argument to ``calculate_cloud``.
+
+* Added ``TaggedItemManager.get_union_by_model`` for looking up items
+  tagged with any one of a list of tags.
+
+* Added ``TagManager.add_tag`` for adding a single extra tag to an
+  object.
+
+* Tag names can now be forced to lowercase before they are saved to the
+  database by adding the appropriate ``FORCE_LOWERCASE_TAGS`` setting to
+  your project's settings module. This feature defaults to being off.
+
+* Fixed a bug where passing non-existent tag names to
+  ``TaggedItemManager.get_by_model`` caused database errors with some
+  backends.
+
+* Added ``tagged_object_list`` generic view for displaying paginated
+  lists of objects for a given model which have a given tag, and
+  optionally related tags for that model.
+
+
+Version 0.1, 30th May 2007:
+---------------------------
+
+Packaged from revision 79 in Subversion; download at
+http://django-tagging.googlecode.com/files/tagging-0.1.zip
+
+* First packaged version using distutils.
+Thanks for downloading django-tagging.
+
+To install it, run the following command inside this directory:
+
+    python setup.py install
+
+Or if you'd prefer you can simply place the included ``tagging``
+directory somewhere on your Python path, or symlink to it from
+somewhere on your Python path; this is useful if you're working from a
+Subversion checkout.
+
+Note that this application requires Python 2.3 or later, and Django
+0.96 or later. You can obtain Python from http://www.python.org/ and
+Django from http://www.djangoproject.com/.
+Django Tagging
+--------------
+
+Copyright (c) 2007, Jonathan Buchanan
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Initially based on code from James Bennett's Cab:
+
+Cab
+---
+
+Copyright (c) 2007, James Bennett
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above
+      copyright notice, this list of conditions and the following
+      disclaimer in the documentation and/or other materials provided
+      with the distribution.
+    * Neither the name of the author nor the names of other
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+include CHANGELOG.txt
+include INSTALL.txt
+include LICENSE.txt
+include MANIFEST.in
+include README.txt
+recursive-include docs *.txt
+recursive-include tagging/tests *.txt
+==============
+Django Tagging
+==============
+
+This is a generic tagging application for Django projects
+
+For installation instructions, see the file "INSTALL.txt" in this
+directory; for instructions on how to use this application, and on
+what it provides, see the file "overview.txt" in the "docs/"
+directory.

File django_tagging.egg-info/PKG-INFO

+Metadata-Version: 1.0
+Name: django-tagging
+Version: 0.4-pre
+Summary: Generic tagging application for Django
+Home-page: http://code.google.com/p/django-tagging/
+Author: Jonathan Buchanan
+Author-email: jonathan.buchanan@gmail.com
+License: UNKNOWN
+Description: UNKNOWN
+Platform: UNKNOWN
+Classifier: Development Status :: 4 - Beta
+Classifier: Environment :: Web Environment
+Classifier: Framework :: Django
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Utilities

File django_tagging.egg-info/SOURCES.txt

+CHANGELOG.txt
+INSTALL.txt
+LICENSE.txt
+MANIFEST.in
+README.txt
+django_tagging.egg-info/PKG-INFO
+django_tagging.egg-info/SOURCES.txt
+django_tagging.egg-info/dependency_links.txt
+django_tagging.egg-info/top_level.txt
+docs/overview.txt
+tagging/__init__.py
+tagging/admin.py
+tagging/fields.py
+tagging/forms.py
+tagging/generic.py
+tagging/managers.py
+tagging/models.py
+tagging/settings.py
+tagging/utils.py
+tagging/views.py
+tagging/templatetags/__init__.py
+tagging/templatetags/tagging_tags.py
+tagging/tests/__init__.py
+tagging/tests/models.py
+tagging/tests/settings.py
+tagging/tests/tags.txt
+tagging/tests/tests.py

File django_tagging.egg-info/dependency_links.txt

+

File django_tagging.egg-info/top_level.txt

+tagging

File docs/overview.txt

+==============
+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. It is possible to group tags together in
+namespaces and use values to store additional information.
+
+.. _`Django`: http://www.djangoproject.com
+
+.. contents::
+   :depth: 3
+
+
+Installation
+============
+
+Installing an official release
+------------------------------
+
+Official releases are made available from
+http://code.google.com/p/django-tagging/
+
+Source distribution
+~~~~~~~~~~~~~~~~~~~
+
+Download the .zip 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.
+
+Windows installer
+~~~~~~~~~~~~~~~~~
+
+A Windows installer is also made available - download the .exe
+distribution file and launch it to install the application.
+
+An uninstaller will also be created, accessible through Add/Remove
+Programs in your Control Panel.
+
+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, perform a `Subversion`_ checkout instead. The following
+command will check the application's development branch out to an
+``tagging-trunk`` directory::
+
+   svn checkout http://django-tagging.googlecode.com/svn/trunk/ tagging-trunk
+
+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, 'pre')
+
+When you want to update your copy of the Django Tagging source code, run
+the command ``svn update`` from within the ``tagging-trunk`` 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 trunk, keep an eye on the `CHANGELOG`_ and the
+   `backwards-incompatible changes wiki page`_ before you update your
+   copy of the source code.
+
+.. _`Subversion`: http://subversion.tigris.org
+.. _`PYTHONPATH`: http://www.python.org/doc/2.5.2/tut/node8.html#SECTION008120000000000000000
+.. _`junction`: http://www.microsoft.com/technet/sysinternals/FileAndDisk/Junction.mspx
+.. _`CHANGELOG`: http://django-tagging.googlecode.com/svn/trunk/CHANGELOG.txt
+.. _`backwards-incompatible changes wiki page`: http://code.google.com/p/django-tagging/wiki/BackwardsIncompatibleChanges
+
+Using Django Tagging in your applications
+-----------------------------------------
+
+Once you've installed Django Tagging and want to use it in your Django
+applications, do the following:
+
+   1. Put ``'tagging'`` in your ``INSTALLED_APPS`` setting.
+   2. Run the command ``manage.py syncdb``.
+
+The ``syncdb`` 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:
+
+FORCE_LOWERCASE_TAGS
+--------------------
+
+Default: ``False``
+
+A boolean that turns on/off forcing of all tag names to lowercase before
+they are saved to the database.
+
+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``.
+The delimiters ':' for namespaces and '=' for values are not counted into
+the tag's length.
+
+**New in developement version**
+
+MAX_TAG_NAMESPACE_LENGTH
+--------------
+
+Default: ``50``
+
+An integer which specifies the maximum length which any namespace is allowed
+to have. This is used for validation in the ``django.contrib.admin``
+application and in any forms automatically generated using ``ModelForm``.
+The delimiter ':' is not counted into the namespace's length.
+
+**New in developement version**
+
+MAX_TAG_NAME_LENGTH
+--------------
+
+Default: ``50``
+
+An integer which specifies the maximum length which any tag name is allowed
+to have. This is used for validation in the ``django.contrib.admin``
+application and in any forms automatically generated using ``ModelForm``.
+
+**New in developement version**
+
+MAX_TAG_VALUE_LENGTH
+--------------
+
+Default: ``50``
+
+An integer which specifies the maximum length which any tag value is allowed
+to have. This is used for validation in the ``django.contrib.admin``
+application and in any forms automatically generated using ``ModelForm``.
+The delimiter '=' is not counted into the value's length.
+
+
+Registering your models
+=======================
+
+**New in developement version**
+
+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`` module and call its
+``register`` function, like so::
+
+   from django.db import models
+
+   import tagging
+
+   class Widget(models.Model):
+       name = models.CharField(max_length=50)
+
+   tagging.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_manger_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
+   []
+
+**New in developement version**
+
+You can also use a ``TagDescriptor`` with a specific namespace. This is a
+simple way to handle many namespace seperated from each athor::
+
+   >>> Widget.hot = TagDescriptor(namespace='hot')
+   >>> Widget.cold = TagDescriptor(namespace='cold')
+   >>> widget.tags = 'toast, hot:melted cheese'
+   >>> widget.tags
+   [<Tag: toast>, <Tag: hot:melted cheese>]
+   >>> widget.hot
+   [<Tag: hot:melted cheese>]
+   >>> widget.cold = 'butter'
+   >>> widget.cold
+   [<Tag: cold:butter>]
+   >>> widget.tags
+   [<Tag: toast>, <Tag: cold:butter>, <Tag: hot:melted cheese>]
+
+``ModelTagManager``
+-------------------
+
+A manager for retrieving tags used by a particular model.
+
+Defines the following methods:
+
+* ``get_query_set()`` -- as this method is redefined, any ``QuerySets``
+  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, with ``count`` and ``font_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 given ``tags``.
+
+  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 to ``obj``, based on its tags. If
+  a ``queryset`` argument is provided, it will be used to restrict the
+  resulting list of model instances.
+
+  If ``num`` is given, a maximum of ``num`` instances will be returned.
+
+* ``with_all(tags, queryset=None, **kwargs)`` -- creates a ``QuerySet``
+  containing model instances which are tagged with *all* the given tags.
+  If a ``queryset`` argument is provided, it will be used as the basis for
+  the resulting ``QuerySet``.
+
+* ``with_any(tags, queryset=None, **kwargs)`` -- creates a ``QuerySet``
+  containing model instances which are tagged with *any* the given tags.
+  If a ``queryset`` argument is provided, it will be used as the basis for
+  the resulting ``QuerySet``.
+
+Tags
+====
+
+Tags are represented by the ``Tag`` model, which lives in the
+``tagging.models`` module.
+
+API reference
+-------------
+
+Fields
+~~~~~~
+
+``Tag`` objects have the following fields:
+
+**New in developement version**
+
+* ``namespace`` -- The namespace of the tag. This can be null.
+* ``name`` -- The name of the tag.
+* ``value`` -- The value of the tag. This can be null.
+
+All fields together must be unique.
+
+Manager functions
+~~~~~~~~~~~~~~~~~
+
+The ``Tag`` model has a custom manager which has the following helper
+methods:
+
+* ``update_tags(obj, tag_names, default_namespace=None, q=None)``
+  -- updates tags associated with an object.
+
+  ``tag_names`` is a string containing tag names with which ``obj``
+  should be tagged.
+
+  If ``tag_names`` is ``None`` or ``''``, the object's tags will be
+  cleared.
+
+  ``default_namespace`` is a namespace that is assigned to all tags
+  in ``tag_names`` that have no namespace specified.
+  See `get_tag_list function`_ for more details.
+
+  ``q`` is a ``Q`` object that limits the selection of the tags before
+  they are checked if they must be removed. This is generally not used
+  by third party developers.
+
+* ``add_tag(obj, tag_name, default_namespace=None)``
+  -- associates a tag with an an object.
+
+  ``tag_name`` is a string containing a tag name with which ``obj``
+  should be tagged.
+
+**New in developement version**
+
+  ``default_namespace`` is a namespace that is assigned to the ``tag_name``
+  if it has no namespace specified.
+  See `get_tag_list function`_ for more details.
+
+* ``get_for_object(obj)`` -- returns a ``QuerySet`` containing all
+  ``Tag`` objects associated with ``obj``.
+
+.. _`usage_for_model method`:
+
+* ``usage_for_model(model, counts=False, min_count=None, filters=None)``
+  -- returns a list of ``Tag`` objects associated with instances of
+  ``model``.
+
+  If ``counts`` is ``True``, a ``count`` attribute will be added to each
+  tag, indicating how many times it has been associated with instances
+  of ``model``.
+
+  If ``min_count`` is given, only tags which have a ``count`` greater
+  than or equal to ``min_count`` will be returned. Passing a value for
+  ``min_count`` implies ``counts=True``.
+
+  To limit the tags (and counts, if specified) returned to those used by
+  a subset of the model's instances, pass a dictionary of field lookups
+  to be applied to ``model`` as the ``filters`` argument.
+
+.. _`usage_for_queryset method`:
+
+* ``usage_for_queryset(queryset, counts=False, min_count=None)``
+  -- returns a list of ``Tag`` objects associated with instances of
+  a model contained in the given ``queryset``.
+
+  If ``counts`` is ``True``, a ``count`` attribute will be added to each
+  tag, indicating how many times it has been associated with instances
+  of ``model``.
+
+  If ``min_count`` is given, only tags which have a ``count`` greater
+  than or equal to ``min_count`` will be returned. Passing a value for
+  ``min_count`` implies ``counts=True``.
+
+.. _`related_for_model method`:
+
+* ``related_for_model(tags, Model, counts=False, min_count=None,
+  wildcard=None, default_namespace=None)`` -- returns a list of tags related
+  to a given list of tags - that is, other tags used by items which have all
+  the given tags.
+
+  If ``counts`` is ``True``, a ``count`` attribute will be added to each
+  tag, indicating the number of items which have it in addition to the
+  given list of tags.
+
+  If ``min_count`` is given, only tags which have a ``count`` greater
+  than or equal to ``min_count`` will be returned. Passing a value for
+  ``min_count`` implies ``counts=True``.
+
+**New in developement version**
+
+  ``wildcard`` can be a string that is used to as a wildcard in ``tags``.
+  See `get_tag_list function`_ for more details.
+
+**New in developement version**
+
+  If ``default_namespace`` is given, it is applied to all ``tags`` that
+  have no namespace specified.  See `get_tag_list function`_ for more details.
+
+.. _`cloud_for_model method`:
+
+* ``cloud_for_model(Model, steps=4, distribution=LOGARITHMIC,
+  filters=None, min_count=None)`` -- returns a list of the distinct
+  ``Tag`` objects associated with instances of ``Model``, each having a
+  ``count`` attribute as above and an additional ``font_size``
+  attribute, for use in creation of a tag cloud (a type of weighted
+  list).
+
+  ``steps`` defines the number of font sizes available - ``font_size``
+  may be an integer between ``1`` and ``steps``, inclusive.
+
+  ``distribution`` defines the type of font size distribution algorithm
+  which will be used - logarithmic or linear. It must be either
+  ``tagging.utils.LOGARITHMIC`` or ``tagging.utils.LINEAR``.
+
+  To limit the tags displayed in the cloud to those associated with a
+  subset of the Model's instances, pass a dictionary of field lookups to
+  be applied to the given Model as the ``filters`` argument.
+
+  To limit the tags displayed in the cloud to those with a ``count``
+  greater than or equal to ``min_count``, pass a value for the
+  ``min_count`` argument.
+
+**New in development version**
+
+* ``usage_for_queryset(queryset, counts=False, min_count=None)`` --
+  Obtains a list of tags associated with instances of a model contained
+  in the given queryset.
+
+  If ``counts`` is True, a ``count`` attribute will be added to each tag,
+  indicating how many times it has been used against the Model class in
+  question.
+
+  If ``min_count`` is given, only tags which have a ``count`` greater
+  than or equal to ``min_count`` will be returned.
+
+  Passing a value for ``min_count`` implies ``counts=True``.
+
+Basic usage
+-----------
+
+Tagging objects and retrieving an object's tags
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Objects may be tagged using the ``update_tags`` helper function::
+
+   >>> from shop.apps.products.models import Widget
+   >>> from tagging.models import Tag
+   >>> widget = Widget.objects.get(pk=1)
+   >>> Tag.objects.update_tags(widget, 'house thing')
+
+Retrieve tags for an object using the ``get_for_object`` helper
+function::
+
+   >>> Tag.objects.get_for_object(widget)
+   [<Tag: house>, <Tag: thing>]
+
+Tags are created, associated and unassociated accordingly when you use
+``update_tags`` and ``add_tag``::
+
+   >>> Tag.objects.update_tags(widget, 'house monkey')
+   >>> Tag.objects.get_for_object(widget)
+   [<Tag: house>, <Tag: monkey>]
+   >>> Tag.objects.add_tag(widget, 'tiles')
+   >>> Tag.objects.get_for_object(widget)
+   [<Tag: house>, <Tag: monkey>, <Tag: tiles>]
+   >>> Tag.objects.update_tags(widget,
+   ... 'banana apple', default_namespace='fruit')
+   >>> Tag.objects.get_for_object(widget)
+   [<Tag: fruit:banana>, <Tag: fruit:apple>]
+
+Clear an object's tags by passing ``None`` or ``''`` to
+``update_tags``::
+
+   >>> Tag.objects.update_tags(widget, None)
+   >>> Tag.objects.get_for_object(widget)
+   []
+
+Retrieving tags used by a particular model
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To retrieve all tags used for a particular model, use the
+``get_for_model`` helper function::
+
+   >>> widget1 = Widget.objects.get(pk=1)
+   >>> Tag.objects.update_tags(widget1, 'house thing')
+   >>> widget2 = Widget.objects.get(pk=2)
+   >>> Tag.objects.update_tags(widget2, 'cheese toast house')
+   >>> Tag.objects.usage_for_model(Widget)
+   [<Tag: cheese>, <Tag: house>, <Tag: thing>, <Tag: toast>]
+
+To get a count of how many times each tag was used for a particular
+model, pass in ``True`` for the ``counts`` argument::
+
+   >>> tags = Tag.objects.usage_for_model(Widget, counts=True)
+   >>> [(tag.name, tag.count) for tag in tags]
+   [('cheese', 1), ('house', 2), ('thing', 1), ('toast', 1)]
+
+To get counts and limit the tags returned to those with counts above a
+certain size, pass in a ``min_count`` argument::
+
+   >>> tags = Tag.objects.usage_for_model(Widget, min_count=2)
+   >>> [(tag.name, tag.count) for tag in tags]
+   [('house', 2)]
+
+You can also specify a dictionary of `field lookups`_ to be used to
+restrict the tags and counts returned based on a subset of the
+model's instances. For example, the following would retrieve all tags
+used on Widgets created by a user named Alan which have a size
+greater than 99::
+
+   >>> Tag.objects.usage_for_model(Widget, filters=dict(size__gt=99, user__username='Alan'))
+
+.. _`field lookups`: http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups
+
+**New in development version**
+
+The ``usage_for_queryset`` method allows you to pass a pre-filtered
+queryset to be used when determining tag usage::
+
+   >>> Tag.objects.usage_for_queryset(Widget.objects.filter(size__gt=99, user__username='Alan'))
+
+Tag input
+---------
+
+Tag input from users is treated as follows:
+
+* If the input doesn't contain any commas or double quotes, it is simply
+  treated as a space-delimited list of tag names.
+
+* If the input does contain either of these characters, we parse the
+  input like so:
+
+  * Groups of characters which appear between double quotes take
+    precedence as multi-word tags (so double quoted tag names may
+    contain commas). An unclosed double quote will be ignored.
+
+  * For the remaining input, if there are any unquoted commas in the
+    input, the remainder will be treated as comma-delimited. Otherwise,
+    it will be treated as space-delimited.
+
+* The first ``'='`` character in an unquoted area of a tag is used to seperate
+  the tag's name from the value. Any ``'='`` character in the tag's value is
+  handled like any athor character.
+
+* The first ``':'`` character in an unquoted area of a tag is used to seperate
+  the namespace from the rest of the tag. Any athor ``':'`` character in the
+  tag is handled like any athor character.
+
+Examples:
+
+====================== ======================================= ==============================================
+Tag input string       Resulting tags                          Notes
+====================== ======================================= ==============================================
+apple ball cat         [``apple``], [``ball``], [``cat``]      No commas, so space delimited
+apple, ball cat        [``apple``], [``ball cat``]             Comma present, so comma delimited
+"apple, ball" cat dog  [``apple, ball``], [``cat``], [``dog``] All commas are quoted, so space delimited
+"apple, ball", cat dog [``apple, ball``], [``cat dog``]        Contains an unquoted comma, so comma delimited
+apple "ball cat" dog   [``apple``], [``ball cat``], [``dog``]  No commas, so space delimited
+"apple" "ball dog      [``apple``], [``ball``], [``dog``]      Unclosed double quote is ignored
+====================== ======================================= ==============================================
+
+=================== ========= =============== ======== ===================================
+Tag input string    Namespace Name            Value    Notes
+=================== ========= =============== ======== ===================================
+apple               ``None``  ``apple``       ``None`` No namespace and no value specified
+fruit:apple         ``fruit`` ``apple``       ``None`` The value defaults to ``None``
+fruit:"apple=tasty" ``fruit`` ``apple=tasty`` ``None`` No value because ``=`` is quoted
+cute:cat:pussy      ``cute``  ``cat:pussy``   ``None`` Only first ``:`` is recognized
+=================== ========= =============== ======== ===================================
+
+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`` -- The ``Tag`` an object is associated with.
+* ``content_type`` -- The ``ContentType`` 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, tags, wildcard=None,
+  default_namespace=None)`` -- creates a ``QuerySet`` containing instances
+  of the specififed model which are tagged with the given tag or tags.
+
+**New in developement version**
+
+  ``wildcard`` can be a string that is used to as a wildcard in ``tags``.
+  See `get_tag_list function`_ for more details.
+
+**New in developement version**
+
+  If ``default_namespace`` is given, it is applied to all ``tags`` that
+  have no namespace specified.  See `get_tag_list function`_ for more details.
+
+* ``get_intersection_by_model(queryset_or_model, tags, wildcard=None,
+  default_namespace=None)`` -- creates a ``QuerySet`` 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 use ``get_by_model`` instead of calling
+  this method directly.
+
+**New in developement version**
+
+  ``wildcard`` can be a string that is used to as a wildcard in ``tags``.
+  See `get_tag_list function`_ for more details.
+
+**New in developement version**
+
+  If ``default_namespace`` is given, it is applied to all ``tags`` that
+  have no namespace specified.  See `get_tag_list function`_ for more details.
+
+* ``get_union_by_model(queryset_or_model, tags, wildcard=None,
+  default_namespace=None)`` -- creates a ``QuerySet`` containing instances
+  of the specified model which are tagged with any tag in a list of tags.
+
+**New in developement version**
+
+  ``wildcard`` can be a string that is used to as a wildcard in ``tags``.
+  See `get_tag_list function`_ for more details.
+
+**New in developement version**
+
+  If ``default_namespace`` is given, it is applied to all ``tags`` that
+  have no namespace specified. See `get_tag_list function`_ for more details.
+
+.. _`get_related method`:
+
+* ``get_related(obj, queryset_or_model, num=None)`` - returns a list of
+  instances of the specified model which share tags with the model
+  instance ``obj``, ordered by the number of shared tags in descending
+  order.
+
+  If ``num`` is given, a maximum of ``num`` instances will be returned.
+
+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>]
+
+Functions which take tags mostly also takes a ``wildcard`` parameter::
+
+   >>> TaggedItem.objects.get_by_model(Widget, 'fruit:*', wildcard='*')
+   [<Widget: pk=3>]
+   >>> TaggedItem.objects.get_by_model(Widget, 'fruit:*=*', wildcard='*')
+   [<Widget: pk=3>, <Widget: pk=4>]
+
+You can quote a wildcard to prevent it from expanding::
+   >>> TaggedItem.objects.get_by_model(Widget, 'fruit:"*"', wildcard='*')
+   []
+
+Functions which take tags mostly also takes a ``default_namespace`` parameter::
+
+   >>> TaggedItem.objects.get_by_model(Widget, 'apple', default_namespace='fruit')
+   [<Widget: pk=3>]
+   >>> TaggedItem.objects.get_by_model(Widget, 'apple=tasty', default_namespace='fruit')
+   [<Widget: pk=4>]
+
+See `get_tag_list function`_ for more details.
+
+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 function`:
+
+``parse_tag_input(input, default_namespace=None, keep_quotes=None)``
+--------------------------------------------------------------------
+
+Parses tag input, with multiple word input being activated and
+delineated by commas and double quotes. Quotes take precedence, so they
+may contain commas.
+
+``default_namespace`` is a namespace that is applied to all tags that have
+no athor namespace defined. If ``default_namespace`` is set to ``fruit``
+and ``input`` is ``apple`` it would be parsed to ``fruit:apple``. But if input
+is ``:apple``, it would be parsed to ``apple`` because an empty namespace
+was specified explicitly.
+
+Returns a sorted list of unique tag names.
+
+See `tag input`_ for more details.
+
+.. _`edit_string_for_tags function`:
+
+``edit_string_for_tags(tags, default_namespace=None, filter_namespaces=None,
+exclude_namespaces=None)``
+----------------------------------------------------------------------------
+Given list of ``Tag`` instances, creates a string representation of the
+list suitable for editing by the user, such that submitting the given
+string representation back without changing it will give the same list
+of tags.
+
+Tag names which contain commas will be double quoted.
+
+If any tag name which isn't being quoted contains whitespace, the
+resulting string of tag names will be comma-delimited, otherwise it will
+be space-delimited.
+
+``default_namespace`` is a namespace that is applied to all tags that have
+no athor namespace defined. If ``default_namespace`` is set to ``fruit``
+and ``input`` is ``apple`` it would be parsed to ``fruit:apple``. But if input
+is ``:apple``, it would be parsed to ``apple`` because an empty namespace
+was specified explicitly.
+
+If the namespace of a given tag is in ``exclude_namespaces`` or not in
+``filter_namespaces``, it will be removed from the resulting string.
+
+.. _`get_tag_list function`:
+
+``get_tag_list(tags, wildcard=None, default_namespace=None)``
+-------------------------------------------------------------
+
+Utility function for accepting tag input in a flexible manner.
+
+If a ``Tag`` object is given, it will be returned in a list as its
+single occupant.
+
+If given, the tag names in the following will be used to create a
+``Tag`` ``QuerySet``:
+
+   * A string, which may contain multiple tag names.
+   * A list or tuple of strings corresponding to tag names.
+   * A list or tuple of integers corresponding to tag ids.
+
+If given, the following will be returned as-is:
+
+   * A list or tuple of ``Tag`` objects.
+   * A ``Tag`` ``QuerySet``.
+
+The parameters ``wildcard`` and ``default_namespace`` are only used if a
+string is given.
+
+``wildcard`` can be any string and will be is used to expand namespaces,
+tag names and values. But this is only possible with whole namespaces, names
+and values and cannot be used to expand parts of them. One wildcard is also
+only used for one part of the tag, this means you cannot match the name and
+the value of a tag with one wildcard.
+
+If a ``wildcard`` is specified but you want to match the exact string
+representation of ``wildcard`` you can double-quote the wildcard.
+
+Examples::
+
+    >>> get_tag_list('fruit:*', wildcard='*')
+    [<Tag fruit:apple>, <Tag fruit:banana>, <Tag: fruit:pineapple>]
+    >>> get_tag_list('fruit:*=*', wildcard='*')
+    [<Tag fruit:apple>, <Tag fruit:apple=tasty>, <Tag fruit:banana>, <Tag fruit:banana=*>, <Tag: fruit:pineapple>]
+    >>> get_tag_list('*:apple=*', wildcard='*')
+    [<Tag fruit:apple>, <Tag fruit:apple=tasty>, <Tag: food:apple>, <Tag: apple=green>]
+    >>> get_tag_list('fruit:*="*"', wildcard='*')
+    [<Tag fruit:banana=*>]
+    >>> get_tag_list('fruit:*apple')
+    []
+
+You can define a namespace with ``default_namespace`` that is applied to all
+tags which have no namespace explicitly specified.
+
+Examples::
+
+    >>> get_tag_list('apple', default_namespace='fruit')
+    [<Tag fruit:apple>]
+    >>> get_tag_list('food:apple', default_namespace='fruit')
+    [<Tag food:apple>]
+    >>> get_tag_list(':apple=green', default_namespace='fruit')
+    [<Tag apple=green>]
+    >>> get_tag_list('apple food:apple :apple=green', default_namespace='fruit')
+    [<Tag apple=green>, <Tag fruit:apple>, <Tag food:apple>]
+
+``calculate_cloud(tags, steps=4, distribution=tagging.utils.LOGARITHMIC)``
+--------------------------------------------------------------------------
+
+Add a ``font_size`` attribute to each tag according to the frequency of
+its use, as indicated by its ``count`` attribute.
+
+``steps`` defines the range of font sizes - ``font_size`` will be an
+integer between 1 and ``steps`` (inclusive).
+
+``distribution`` defines the type of font size distribution algorithm
+which will be used - logarithmic or linear. It must be one of
+``tagging.utils.LOGARITHMIC`` or ``tagging.utils.LINEAR``.
+
+
+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.
+
+You can assign more than one ``TagField`` to a model if you want to. But you
+need to specify on every field a different namespace::
+
+    class Food(models.Model):
+       ...
+       tags = TagField()
+       taste = TagField(namespace='taste')
+
+Now you can specify tags on both fields. But tags that have a different
+namespace than the field they are assigned to will simply be ignored. The
+same happens to tags which have a namespace that is present on anathor
+``TagField``. Even if the ``TagField`` where the tag is assigned to has
+no specific namespace.
+
+Example::
+
+    >>> f = Food.object.get(...)
+    >>> f.taste = 'sweet bitter'
+    >>> f.tags
+    u''
+    >>> f.taste
+    u'bitter sweet'
+    >>> f.tags = 'size:big green taste:sour'
+    >>> Tag.objects.get_for_object(f)
+    [<Tag: green>, <Tag: taste:bitter>, <Tag: taste:sweet>, <Tag: size:big>]
+    >>> f.taste = 'size:small'
+    >>> f.tags
+    u'green size:big'
+    >>> f.taste
+    u''
+
+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.
+
+.. _`forms library`: http://docs.djangoproject.com/en/dev/topics/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.tagged_object_list``
+------------------------------------
+
+**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_detail.object_list`` view, which takes a
+model and a tag as its arguments (in addition to the other optional
+arguments supported by ``object_list``), building the appropriate
+``QuerySet`` for you instead of expecting one to be passed in.
+
+**Required arguments:**
+
+   * ``queryset_or_model``: A ``QuerySet`` or Django model class for the
+     object which will be listed.
+
+   * ``tag``: The tag which objects of the given model must have in
+     order to be listed.
+
+**Optional arguments:**
+
+Please refer to the `object_list documentation`_ for additional optional
+arguments which may be given.
+
+   * ``related_tags``: If ``True``, a ``related_tags`` context variable
+     will also contain tags related to the given tag for the given
+     model.
+
+   * ``related_tag_counts``: If ``True`` and ``related_tags`` is
+     ``True``, each related tag will have a ``count`` attribute
+     indicating the number of items which have it in addition to the
+     given tag.
+
+**Template context:**
+
+Please refer to the `object_list documentation`_ for  additional
+template context variables which may be provided.
+
+   * ``tag``: The ``Tag`` instance for the given tag.
+
+.. _`object_list documentation`: http://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-list-detail-object-list
+
+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 tagged_object_list
+
+   from shop.apps.products.models import Widget
+
+   urlpatterns = patterns('',
+       url(r'^widgets/tag/(?P<tag>[^/]+)/$',
+           tagged_object_list,
+           dict(queryset_or_model=Widget, paginate_by=10, allow_empty=True,
+                template_object_name='widget'),
+           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 tagged_object_list
+
+   def tagged_people(request, country_code, tag):
+       queryset = People.objects.filter(country__code=country_code)
+       return tagged_object_list(request, queryset, tag, paginate_by=25,
+           allow_empty=True, template_object_name='people')
+
+
+Template tags
+=============
+
+The ``tagging.templatetags.tagging_tags`` module defines a number of
+template tags which may be used to work with tags.
+
+Tag reference
+-------------
+
+tags_for_model
+~~~~~~~~~~~~~~
+
+Retrieves a list of ``Tag`` objects associated with a given model and
+stores them in a context variable.
+
+Usage::
+
+   {% tags_for_model [model] as [varname] %}
+
+The model is specified in ``[appname].[modelname]`` format.
+
+Extended usage::
+
+   {% tags_for_model [model] as [varname] with counts %}
+
+If specified - by providing extra ``with counts`` arguments - adds a
+``count`` attribute to each tag containing the number of instances of
+the given model which have been tagged with it.
+
+Examples::
+
+   {% tags_for_model products.Widget as widget_tags %}
+   {% tags_for_model products.Widget as widget_tags with counts %}
+
+tag_cloud_for_model
+~~~~~~~~~~~~~~~~~~~
+
+Retrieves a list of ``Tag`` objects for a given model, with tag cloud
+attributes set, and stores them in a context variable.
+
+Usage::
+
+   {% tag_cloud_for_model [model] as [varname] %}
+
+The model is specified in ``[appname].[modelname]`` format.
+
+Extended usage::
+
+   {% tag_cloud_for_model [model] as [varname] with [options] %}
+
+Extra options can be provided after an optional ``with`` argument, with
+each option being specified in ``[name]=[value]`` format. Valid extra
+options are:
+
+   ``steps``
+      Integer. Defines the range of font sizes.
+
+   ``min_count``
+      Integer. Defines the minimum number of times a tag must have
+      been used to appear in the cloud.
+
+   ``distribution``
+      One of ``linear`` or ``log``. Defines the font-size
+      distribution algorithm to use when generating the tag cloud.
+
+Examples::
+
+   {% tag_cloud_for_model products.Widget as widget_tags %}
+   {% tag_cloud_for_model products.Widget as widget_tags with steps=9 min_count=3 distribution=log %}
+
+tags_for_object
+~~~~~~~~~~~~~~~
+
+Retrieves a list of ``Tag`` objects associated with an object and stores
+them in a context variable.
+
+Usage::
+
+   {% tags_for_object [object] as [varname] %}
+
+Example::
+
+    {% tags_for_object foo_object as tag_list %}
+
+tagged_objects
+~~~~~~~~~~~~~~
+
+Retrieves a list of instances of a given model which are tagged with a
+given ``Tag`` and stores them in a context variable.
+
+Usage::
+
+   {% tagged_objects [tag] in [model] as [varname] %}
+
+The model is specified in ``[appname].[modelname]`` format.
+
+The tag must be an instance of a ``Tag``, not the name of a tag.
+
+Example::
+
+    {% tagged_objects comedy_tag in tv.Show as comedies %}
+"""
+Based entirely on Django's own ``setup.py``.
+"""
+import os
+from distutils.command.install import INSTALL_SCHEMES
+from distutils.core import setup
+
+def fullsplit(path, result=None):
+    """
+    Split a pathname into components (the opposite of os.path.join) in a
+    platform-neutral way.
+    """
+    if result is None:
+        result = []
+    head, tail = os.path.split(path)
+    if head == '':
+        return [tail] + result
+    if head == path:
+        return result
+    return fullsplit(head, [tail] + result)
+
+# Tell distutils to put the data_files in platform-specific installation
+# locations. See here for an explanation:
+# http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb
+for scheme in INSTALL_SCHEMES.values():
+    scheme['data'] = scheme['purelib']
+
+# Compile the list of packages available, because distutils doesn't have
+# an easy way to do this.
+packages, data_files = [], []
+root_dir = os.path.dirname(__file__)
+tagging_dir = os.path.join(root_dir, 'tagging')
+pieces = fullsplit(root_dir)
+if pieces[-1] == '':
+    len_root_dir = len(pieces) - 1
+else:
+    len_root_dir = len(pieces)
+
+for dirpath, dirnames, filenames in os.walk(tagging_dir):
+    # Ignore dirnames that start with '.'
+    for i, dirname in enumerate(dirnames):
+        if dirname.startswith('.'): del dirnames[i]
+    if '__init__.py' in filenames:
+        packages.append('.'.join(fullsplit(dirpath)[len_root_dir:]))
+    elif filenames:
+        data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]])
+
+# Dynamically calculate the version based on tagging.VERSION
+version_tuple = (0, 4, 'pre')
+if version_tuple[2] is not None:
+    version = "%d.%d_%s" % version_tuple
+else:
+    version = "%d.%d" % version_tuple[:2]
+
+setup(
+    name = 'django-tagging',
+    version = version,
+    description = 'Generic tagging application for Django',
+    author = 'Jonathan Buchanan',
+    author_email = 'jonathan.buchanan@gmail.com',
+    url = 'http://code.google.com/p/django-tagging/',
+    packages = packages,
+    data_files = data_files,
+    classifiers = ['Development Status :: 4 - Beta',
+                   'Environment :: Web Environment',
+                   'Framework :: Django',
+                   'Intended Audience :: Developers',
+                   'License :: OSI Approved :: BSD License',
+                   'Operating System :: OS Independent',
+                   'Programming Language :: Python',
+                   'Topic :: Utilities'],
+)

File tagging/__init__.py

+from django.utils.translation import ugettext as _
+
+from tagging.managers import ModelTaggedItemManager, TagDescriptor
+
+VERSION = (0, 4, 'pre')
+
+class AlreadyRegistered(Exception):
+    """
+    An attempt was made to register a model more than once.
+    """
+    pass
+
+registry = []
+
+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.__name__)
+    registry.append(model)
+
+    # Add tag descriptor
+    setattr(model, tag_descriptor_attr, TagDescriptor())
+
+    # Add custom manager
+    ModelTaggedItemManager().contribute_to_class(model,
+                                                 tagged_item_manager_attr)

File tagging/__init__.pyc

Binary file added.

File tagging/admin.py

+from django.contrib import admin
+from tagging.models import Tag, TaggedItem
+from tagging.forms import TagAdminForm
+
+class TagAdmin(admin.ModelAdmin):
+    form = TagAdminForm
+
+admin.site.register(TaggedItem)
+admin.site.register(Tag, TagAdmin)
+
+
+
+

File tagging/admin.pyc

Binary file added.

File tagging/fields.py

+"""
+A custom Model Field for tagging.
+"""
+from django.db.models import signals, Q
+from django.db.models.fields import CharField
+from django.utils.translation import ugettext_lazy as _
+
+from tagging import settings
+from tagging.models import Tag
+from tagging.utils import edit_string_for_tags, get_tag_parts, parse_tag_input
+
+try:
+    set
+except NameError:
+    from sets import Set as set
+
+class TagField(CharField):
+    """
+    A "special" character field that actually works as a relationship to tags
+    "under the hood". This exposes a space-separated string of tags, but does
+    the splitting/reordering/etc. under the hood.
+
+    This field will only accept tags from a specific namespace if the
+    ``namespace`` parameter is given. Any athor tag that is assigned will be
+    thrown away.
+    """
+    def __init__(self, *args, **kwargs):
+        self.namespace = kwargs.get('namespace', None)
+        if 'namespace' in kwargs:
+            del kwargs['namespace']
+        kwargs['max_length'] = kwargs.get('max_length', 255)
+        kwargs['blank'] = kwargs.get('blank', True)
+        kwargs['default'] = kwargs.get('default', '')
+        super(TagField, self).__init__(*args, **kwargs)
+
+    def contribute_to_class(self, cls, name):
+        super(TagField, self).contribute_to_class(cls, name)
+
+        # Make this object the descriptor for field access.
+        setattr(cls, self.name, self)
+
+        # Save tags back to the database post-save
+        signals.post_save.connect(self._save, cls, True)
+
+        # Update tags from Tag objects post-init
+        signals.post_init.connect(self._update, cls, True)
+
+    def _get_edit_string_for_tags(self, owner=None, instance=None):
+        kwargs = {'default_namespace': self.namespace}
+        # if there are more than one tag field on this model,
+        # skip the tags with namespaces of athor fields.
+        # Thats their domain.
+        if self.namespace is not None:
+            kwargs['filter_namespaces'] = (self.namespace,)
+        elif self._has_instance_multiple_tag_fields:
+            kwargs['exclude_namespaces'] = self._foreign_namespaces
+
+        # Handle access on the model (i.e. Link.tags)
+        if instance is None:
+            queryset = Tag.objects.usage_for_model(owner)
+        # Handle access on the model instance
+        else:
+            queryset = Tag.objects.get_for_object(instance)
+        return edit_string_for_tags(queryset, **kwargs)
+
+    def __get__(self, instance, owner=None):
+        """
+        Tag getter. Returns an instance's tags if accessed on an instance, and
+        all of a model's tags if called on a class. That is, this model::
+
+           class Link(models.Model):
+               ...
+               tags = TagField()
+
+        Lets you do both of these::
+
+           >>> l = Link.objects.get(...)
+           >>> l.tags
+           'tag1 tag2 tag3'
+
+           >>> Link.tags
+           'tag1 tag2 tag3 tag4'
+
+        """
+        self._init(owner or instance)
+        if instance is None:
+            return self._get_edit_string_for_tags(owner=owner)
+        return self._get_instance_tag_cache(instance)
+
+    def __set__(self, instance, value):
+        """
+        Set an object's tags.
+        """
+        if instance is None:
+            raise AttributeError(
+                _('%s can only be set on instances.') % self.name)
+        if value is None:
+            value = u''
+        if settings.FORCE_LOWERCASE_TAGS:
+            value = value.lower()
+        self._set_instance_tag_cache(instance, value)
+
+    def _init(self, instance):
+        """
+        Check if the model has more than one tag field and collects the default
+        namespaces of athor tag fields.
+        """
+        # check if already initialized
+        if  hasattr(self, '_has_instance_multiple_tag_fields') and \
+            hasattr(self, '_foreign_namespaces'):
+                return
+        # any athor tag fields of the model
+        tag_fields = []
+        for field in instance._meta.fields:
+            if isinstance(field, self.__class__) and field is not self:
+                tag_fields.append(field)
+        self._foreign_namespaces = set()
+        self._has_instance_multiple_tag_fields = False
+        if len(tag_fields):
+            self._has_instance_multiple_tag_fields = True
+            for field in tag_fields:
+                if  field.namespace is not None and\
+                    field.namespace != self.namespace:
+                    self._foreign_namespaces.add(field.namespace)
+
+    def _save(self, **kwargs): #signal, sender, instance):
+        """
+        Save tags back to the database
+        """
+        instance = kwargs['instance']
+        tags = self._get_instance_tag_cache(kwargs['instance'])
+        q = Q()
+        if self.namespace is not None:
+            q &= Q(namespace=self.namespace)
+        elif self._has_instance_multiple_tag_fields and \
+                self._foreign_namespaces:
+            q &= ~Q(namespace__in=self._foreign_namespaces)
+        Tag.objects.update_tags(instance, tags, q=q,
+            default_namespace=self.namespace)
+
+    def _update(self, **kwargs): #signal, sender, instance):
+        """
+        Update tag cache from TaggedItem objects.
+        """
+        instance = kwargs['instance']
+        self._init(instance)
+        self._update_instance_tag_cache(instance)
+
+    def __delete__(self, instance):
+        """
+        Clear all of an object's tags.
+        """
+        self._set_instance_tag_cache(instance, '')
+
+    def _get_instance_tag_cache(self, instance):
+        """
+        Helper: get an instance's tag cache.
+        """
+        return getattr(instance, '_%s_cache' % self.attname, None)
+
+    def _set_instance_tag_cache(self, instance, tags):
+        """
+        Helper: set an instance's tag cache.
+        """
+        self._init(instance)
+        # If there is a tag field with a namespace, make sure that this field
+        # only gets the tags that are allowed.
+        if tags and (
+                self._has_instance_multiple_tag_fields or
+                self.namespace is not None
+            ):
+            kwargs = {'default_namespace': self.namespace}
+            if  self.namespace is None:
+                kwargs['exclude_namespaces'] = self._foreign_namespaces
+            else:
+                kwargs['filter_namespaces'] = (self.namespace,)
+            tags = edit_string_for_tags(tags, **kwargs)
+        setattr(instance, '_%s_cache' % self.attname, tags)
+
+    def _update_instance_tag_cache(self, instance):
+        """
+        Helper: update an instance's tag cache from actual Tags.
+        """
+        # for an unsaved object, leave the default value alone
+        if instance.pk is not None:
+            tags = self._get_edit_string_for_tags(instance=instance)
+            self._set_instance_tag_cache(instance, tags)
+
+    def get_internal_type(self):
+        return 'CharField'
+
+    def formfield(self, **kwargs):
+        from tagging import forms
+        defaults = {
+            'form_class': forms.TagField,
+            'default_namespace': self.namespace,
+        }
+        defaults.update(kwargs)
+        return super(TagField, self).formfield(**defaults)
+
+
+def validate_tag_fields(sender, **kwargs):
+    '''
+    Validates ``TagField``s on models.
+    '''
+    namespaces = set()
+    for field in sender._meta.fields:
+        if isinstance(field, TagField):
+            if field.namespace in namespaces:
+                import sys
+                from django.core.management.color import color_style
+                style = color_style()
+                e = (
+                    u"You specified more than one tag field with the "
+                    u"namespace '%s' on the model '%s.%s'. Please make "
+                    u"sure that there are only tag fields with different "
+                    u"namespaces on the same model." % (
+                        field.namespace,
+                        sender._meta.app_label,
+                        sender._meta.object_name)
+                )
+                sys.stderr.write(style.ERROR(str('Error: %s\n' % e)))
+                sys.exit(1)
+            namespaces.add(field.namespace)
+
+signals.class_prepared.connect(validate_tag_fields)

File tagging/fields.pyc

Binary file added.

File tagging/forms.py

+"""
+Tagging components for Django's form library.
+"""
+from django import forms
+from django.utils.translation import ugettext as _
+
+from tagging import settings
+from tagging.models import Tag
+from tagging.utils import check_tag_length, get_tag_parts, parse_tag_input
+
+class TagAdminForm(forms.ModelForm):
+    class Meta:
+        model = Tag
+
+    def _clean_field(self, field_name, max_length, error_msg):
+        value = self.cleaned_data[field_name]
+        if '"' in value:
+            raise forms.ValidationError(
+                _("""The '"' character is not allowed."""))
+        if max_length > 0 and len(value) > max_length:
+            raise forms.ValidationError(error_msg % max_length)
+        return value
+
+    def clean(self):
+        if settings.MAX_TAG_LENGTH:
+            total_length = sum((
+                len(self.cleaned_data.get('namespace', '')),
+                len(self.cleaned_data.get('name', '')),
+                len(self.cleaned_data.get('value', '')),
+            ))
+            if total_length > settings.MAX_TAG_LENGTH:
+                raise forms.ValidationError(
+                    _('A tag may be no more than %s characters long.') %
+                        settings.MAX_TAG_LENGTH)
+        return self.cleaned_data
+
+    def clean_namespace(self):
+        return self._clean_field('namespace', settings.MAX_TAG_NAMESPACE_LENGTH,
+             _('A tag\'s namespace may be no more than %s characters long.'))
+
+    def clean_name(self):
+        return self._clean_field('name', settings.MAX_TAG_NAME_LENGTH,
+            _('A tag\'s name may be no more than %s characters long.'))
+
+    def clean_value(self):
+        return self._clean_field('value', settings.MAX_TAG_VALUE_LENGTH,
+            _('A tag\'s value may be no more than %s characters long.'))
+
+class TagField(forms.CharField):
+    """
+    A ``CharField`` which validates that its input is a valid list of
+    tag names and checks the allowed length of the tag parts.
+    """
+    def __init__(self, *args, **kwargs):
+        if 'default_namespace' in kwargs:
+            self.default_namespace = kwargs.pop('default_namespace')
+        else:
+            self.default_namespace = None
+        super(TagField, self).__init__(*args, **kwargs)
+    def clean(self, value):
+        value = super(TagField, self).clean(value)
+        if value == u'':
+            return value
+        for tag_name in parse_tag_input(value, default_namespace=self.default_namespace):
+            try:
+                check_tag_length(get_tag_parts(tag_name))
+            except ValueError, e:
+                if len(e.args) < 3:
+                    raise
+                part, max_len = e.args[1:3]
+                if part == 'tag':
+                    raise forms.ValidationError(_('Each tag may be no more than %s characters long.') % max_len)
+                elif part == 'namespace':
+                    raise forms.ValidationError(_('Each tag\'s namespace may be no more than %s characters long.') % max_len)
+                elif part == 'name':
+                    raise forms.ValidationError(_('Each tag\'s name may be no more than %s characters long.') % max_len)
+                elif part == 'value':
+                    raise forms.ValidationError(_('Each tag\'s value may be no more than %s characters long.') % max_len)
+                else:
+                    raise
+        return value

File tagging/forms.pyc

Binary file added.

File tagging/generic.py

+from django.contrib.contenttypes.models import ContentType
+
+def fetch_content_objects(tagged_items, select_related_for=None):
+    """
+    Retrieves ``ContentType`` and content objects for the given list of
+    ``TaggedItems``, grouping the retrieval of content objects by model
+    type to reduce the number of queries executed.
+
+    This results in ``number_of_content_types + 1`` queries rather than
+    the ``number_of_tagged_items * 2`` queries you'd get by iterating
+    over the list and accessing each item's ``object`` attribute.
+
+    A ``select_related_for`` argument can be used to specify a list of
+    of model names (corresponding to the ``model`` field of a
+    ``ContentType``) for which ``select_related`` should be used when
+    retrieving model instances.
+    """
+    if select_related_for is None: select_related_for = []
+
+    # Group content object pks by their content type pks
+    objects = {}
+    for item in tagged_items:
+        objects.setdefault(item.content_type_id, []).append(item.object_id)
+
+    # Retrieve content types and content objects in bulk
+    content_types = ContentType._default_manager.in_bulk(objects.keys())
+    for content_type_pk, object_pks in objects.iteritems():
+        model = content_types[content_type_pk].model_class()
+        if content_types[content_type_pk].model in select_related_for:
+            objects[content_type_pk] = model._default_manager.select_related().in_bulk(object_pks)
+        else:
+            objects[content_type_pk] = model._default_manager.in_bulk(object_pks)
+
+    # Set content types and content objects in the appropriate cache
+    # attributes, so accessing the 'content_type' and 'object'
+    # attributes on each tagged item won't result in further database
+    # hits.
+    for item in tagged_items:
+        item._object_cache = objects[item.content_type_id][item.object_id]
+        item._content_type_cache = content_types[item.content_type_id]

File tagging/managers.py

+"""
+Custom managers for Django models registered with the tagging
+application.
+"""
+from django.contrib.contenttypes.models import ContentType
+from django.db import models
+
+from tagging.models import Tag, TaggedItem
+from tagging.utils import edit_string_for_tags
+
+class ModelTagManager(models.Manager):
+    """
+    A manager for retrieving tags for a particular model.
+    """
+    def get_query_set(self):
+        ctype = ContentType.objects.get_for_model(self.model)
+        return Tag.objects.filter(
+            items__content_type__pk=ctype.pk).distinct()
+
+    def cloud(self, *args, **kwargs):
+        return Tag.objects.cloud_for_model(self.model, *args, **kwargs)
+
+    def related(self, tags, *args, **kwargs):
+        return Tag.objects.related_for_model(tags, self.model, *args, **kwargs)
+
+    def usage(self, *args, **kwargs):
+        return Tag.objects.usage_for_model(self.model, *args, **kwargs)
+
+class ModelTaggedItemManager(models.Manager):
+    """
+    A manager for retrieving model instances based on their tags.
+    """
+    def related_to(self, obj, queryset=None, num=None):
+        if queryset is None:
+            return TaggedItem.objects.get_related(obj, self.model, num=num)
+        else:
+            return TaggedItem.objects.get_related(obj, queryset, num=num)
+
+    def with_all(self, tags, queryset=None, **kwargs):
+        if queryset is None:
+            return TaggedItem.objects.get_by_model(self.model, tags, **kwargs)
+        else:
+            return TaggedItem.objects.get_by_model(queryset, tags, **kwargs)
+
+    def with_any(self, tags, queryset=None, **kwargs):
+        if queryset is None:
+            return TaggedItem.objects.get_union_by_model(
+                self.model, tags, **kwargs)
+        else:
+            return TaggedItem.objects.get_union_by_model(
+                queryset, tags, **kwargs)
+
+class TagDescriptor(object):
+    """
+    A descriptor which provides access to a ``ModelTagManager`` for
+    model classes and simple retrieval, updating and deletion of tags
+    for model instances.
+
+    You can limit the actions made by the descriptor to a specific namespace
+    through the ``namespace`` parameter.
+    """
+    def __init__(self, **kwargs):
+        self.namespace = kwargs.get('namespace', None)
+
+    def __get__(self, instance, owner):
+        if not instance:
+            tag_manager = ModelTagManager()
+            tag_manager.model = owner
+            queryset = tag_manager
+        else:
+            queryset = Tag.objects.get_for_object(instance)
+        if self.namespace is not None:
+            queryset = queryset.filter(namespace=self.namespace)
+        return queryset
+
+    def __set__(self, instance, value):
+        kwargs = {'default_namespace': self.namespace}
+        q = None
+        if  self.namespace is not None:
+            q = models.Q(namespace=self.namespace)
+            kwargs['filter_namespaces'] = (self.namespace,)
+        value = edit_string_for_tags(value or (), **kwargs)
+        Tag.objects.update_tags(instance, value, q=q,
+            default_namespace=self.namespace)
+
+    def __delete__(self, instance):
+        q = None
+        if  self.namespace is not None:
+            q = models.Q(namespace=self.namespace)
+        Tag.objects.update_tags(instance, None, q=q,
+            default_namespace=self.namespace)

File tagging/managers.pyc

Binary file added.

File tagging/models.py

+"""
+Models and managers for generic tagging.
+"""
+# Python 2.3 compatibility
+try:
+    set
+except NameError:
+    from sets import Set as set
+
+from django.contrib.contenttypes import generic
+from django.contrib.contenttypes.models import ContentType
+from django.db import connection, models
+from django.utils.translation import ugettext_lazy as _
+
+from tagging import settings
+from tagging.utils import calculate_cloud, get_tag_list, get_tag_parts, get_queryset_and_model, normalize_tag_part, parse_tag_input
+from tagging.utils import LOGARITHMIC
+
+qn = connection.ops.quote_name
+
+############
+# Managers #
+############
+
+class TagManager(models.Manager):
+    def update_tags(self, obj, tag_names, default_namespace=None, q=None):
+        """
+        Update tags associated with an object.
+
+        Accepts a ``default_namespace`` parameter that is assigned to tags
+        with no namespace specified.
+        """
+        ctype = ContentType.objects.get_for_model(obj)
+        current_tags = self.filter(items__content_type__pk=ctype.pk,
+            items__object_id=obj.pk)
+        if q is not None:
+            current_tags = current_tags.filter(q)
+        current_tags = list(current_tags)
+        updated_tag_names = parse_tag_input(tag_names,
+            default_namespace=default_namespace)
+        if settings.FORCE_LOWERCASE_TAGS:
+            updated_tag_names = [t.lower() for t in updated_tag_names]
+
+        # Remove tags which no longer apply
+        tags_for_removal = [tag for tag in current_tags \
+                            if unicode(tag) not in updated_tag_names]
+        if len(tags_for_removal):
+            TaggedItem._default_manager.filter(content_type__pk=ctype.pk,
+                object_id=obj.pk, tag__in=tags_for_removal).delete()
+        # Add new tags
+        current_tag_names = [unicode(tag) for tag in current_tags]
+        for tag_name in updated_tag_names:
+            if tag_name not in current_tag_names:
+                tag, created = self.get_or_create(**get_tag_parts(tag_name))
+                TaggedItem._default_manager.create(tag=tag, object=obj)
+
+    def add_tag(self, obj, tag_name, default_namespace=None):
+        """
+        Associates the given object with a tag.
+
+        Accepts a ``default_namespace`` parameter that is assigned to a tag
+        with no namespace specified.