- Author:
- macmichael01
- Posted:
- February 7, 2008
- Language:
- Python
- Version:
- .96
- Score:
- 4 (after 4 ratings)
This is my personal tagging system that I have created. It is intended to be used for multiple applications. This tagging system also has a build in tag cloud that will generate based on the most frequently used tags that you have used or based on the number of clicks users have clicked on a particular tag.
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | ## Middleware.py
from tags.models import Tag
# must have a url expression similar to the one below in order to use this
# (r'^tags/(?P<tag>[-\w]+)/$','show_view'),
class TagClicksMiddleware(object):
"""
This middleware class increments the
number of times that a user clicks on a particular tag
"""
def process_response(self, request, response):
# this is kinda hackish but it works.
try:
tag_url = request.META['PATH_INFO'].split('/tags/')
tag_url = tag_url[1][:-1]
tags = Tag.objects.get(slug__exact=tag_url)
tags.clicks = tags.clicks + 1
tags.save()
except:
return response
return response
## models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
class Tag(models.Model):
"""
This is the table that holds our tag names associated with our blog
"""
name = models.CharField(max_length=25)
slug = models.SlugField(prepopulate_from=('name',))
clicks = models.IntegerField(null=True, default=0)
content_type = models.ForeignKey(ContentType,)
class Meta:
db_table = 'tags'
verbose_name = 'tag'
verbose_name_plural = 'tags'
class Admin:
fields = (
('Tag Form', {
'fields': ('name', 'slug', 'content_type')
}),
)
list_display = ('name', 'clicks', 'content_type')
list_filter = ('content_type',)
search_fields = ['name', 'content_type']
ordering = ['name']
def get_absolute_url(self):
"""Returns the associated tag URl"""
return "/%s/tags/%s/" % (self.content_type.app_label,self.slug)
def __str__(self):
return '%s' % self.name
## tag_processor.py
from django.db.models import get_model
from tags.models import Tag
def tag_cloud_processor(model_name, buckets=4, base_font_size=8,cloud_size=12):
"""
Tag cloud processor returns the most used tags for a particular application.
"""
if model_name:
try:
tag_list = Tag.objects.filter(content_type__app_label__exact=model_name)[:cloud_size]
except:
tag_list = None
tag_range = []
thresholds = []
tags = []
if tag_list:
for tag in tag_list:
tag_range.append(float(getattr(tag, model_name).count()))
max_tag = max(tag_range) or None
min_tag = min(tag_range) or None
if max_tag and min_tag:
delta = (max_tag - min_tag) / float(buckets)
for i in range(1,buckets + 1):
thresh_value = min_tag + i * delta
thresholds.append(thresh_value)
for tag in tag_list:
for bucket in range(1,buckets + 1):
if float(getattr(tag, model_name).count()) <= thresholds[bucket]:
tags.append({"tag":tag, "font_size":(base_font_size + bucket * 2)})
break
return tags
else:
return []
else:
return []
else:
return []
# must have a url expression similar to the one below in order to use this function
# (r'^tags/(?P<tag>[-\w]+)/$','show_view'),
def popular_tag_cloud(buckets=4, base_font_size=8,cloud_size=12):
"""
Tag cloud processor that returns a list of the top tags that users have clicked.
"""
try:
tag_clicks = Tag.objects.filter(clicks__gte=1).order_by('clicks')[:cloud_size]
tag_filter = [tag.clicks for tag in tag_clicks]
tag_list = Tag.objects.filter(clicks__in=tag_filter)[:cloud_size]
except:
tag_list = None
tag_range = []
thresholds = []
tags = []
if tag_list:
for tag in tag_list:
tag_range.append(float(tag.clicks))
max_tag = max(tag_range) or None
min_tag = min(tag_range) or None
if max_tag and min_tag:
delta = (max_tag - min_tag) / float(buckets)
for i in range(1, buckets + 1):
thresh_value = min_tag + i * delta
thresholds.append(thresh_value)
for tag in tag_list:
for bucket in range(1, buckets + 1):
if tag.clicks <= thresholds[bucket]:
tags.append({"tag":tag, "font_size":(base_font_size + bucket * 2)})
break
return tags
else:
return []
else:
return []
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Wouldn't it be easier just to use
django-tagging
?#
nah
#
hi
could you provide maybe some more info on the exact usage of that snippet?
i've saved all the files, packed them into the installed apps in settings.py and an appropriate menue in the admin interface shows up too, but.. how can i tag now specific entries of a blog?
i tried by adding a
from project.tag.models import Tag
to my own models.py and a
tag = Tag()
in my class, doesn't show effect.
and adding tags doesn't work either. there's the form with name, slug and content type, but all combinations just throw "Please correct the error below." :¦
#
You should add a m2m field into you model that you are trying to relate it to. I did not code a TagField() so you cannot use tag = Tag().
So do something similar to this:
tags = models.ManyToManyField('Tag', limit_choices_to={'content_type__app_label': 'SOME_APP_NAME'}, null=True, blank=True)
#
Please login first before commenting.