Skip to content

Instantly share code, notes, and snippets.

@smilesh
Last active December 15, 2015 14:49
Show Gist options
  • Save smilesh/5277585 to your computer and use it in GitHub Desktop.
Save smilesh/5277585 to your computer and use it in GitHub Desktop.
To solve Django-Taggit limitation such as unicode slugify and generic foreignkeys integer problems, I customize and inherit some code as below. It provides unicode slugify based on changing django default slugify into unicode slugify module and string object id for GFK
from django.db import models
from django.utils.translation import ugettext_lazy as _
from taggit.models import Tag, ItemBase
# it is required to support unicode tags slugify
# https://github.com/mozilla/unicode-slugify
from slugify import slugify as default_slugify
class UserContents(models.Model):
id = models.CharField("Content ID", max_length=50, primary_key=True, blank=True)
title = models.CharField("Content Title", max_length=140, default='', null=True, blank=True)
description = models.TextField("Content Description", max_length=2000, default='', null=True, blank=True)
# it provides custom TaggedItem by through attribute
tags = TaggableManager(through=UserContentsTaggedItem)
datetime_modified = models.DateTimeField(null=False, auto_now=True)
datetime_created = models.DateTimeField(null=False, blank=True)
class TagExtended(Tag):
# store created datetime with tag to analyze tagging data
datetime_created = models.DateTimeField(auto_now_add = True)
# inherit slugify from TagBase
def slugify(self, tag, i=None):
slug = default_slugify(tag)
if i is not None:
slug += "_%d" % i
return slug
class UserContentsTaggedItem(ItemBase):
tag = models.ForeignKey('TagExtended', related_name="%(app_label)s_%(class)s_tagged_items")
# store created datetime with tagged contents to analyze tagging data
datetime_created = models.DateTimeField(auto_now_add = True)
# it supports string pk of content_object
object_id = models.CharField(verbose_name=_('Object id'), max_length=100, db_index=True)
content_object = models.ForeignKey(UserContents)
@classmethod
def tags_for(cls, model, instance=None):
if instance is not None:
return cls.tag_model().objects.filter(**{
'%s__content_object' % cls.tag_relname(): instance
})
return cls.tag_model().objects.filter(**{
'%s__content_object__isnull' % cls.tag_relname(): False
}).distinct()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment