I have a simple bookmarks model based on the one in James Bennett's <a
href="
http://code.google.com/p/cab/source/browse/trunk/models.py?
r=130">Cab</a> application. I'm using a generic relation so it can
live in its own app and a user can bookmark any object on the site
(I'm planning on reusing this app on a couple projects). I'm running
into a problem creating an {% if_bookmarked %} template tag.
When I load the tag library I get this error: 'bookmarks' is not a
valid tag library: Could not load template library from
django.templatetags.bookmarks, No module named models
Here's what the tag module looks like:
from django import template
from django.contrib.contenttypes.models import ContentType
from bookmarks.models import Bookmark
class IfBookmarkedNode(template.Node):
def __init__(self, user, obj, nodelist_true, nodelist_false):
self.nodelist_true = nodelist_true
self.nodelist_false = nodelist_false
self.user_id = template.Variable(user_id)
self.obj = template.Variable(obj)
def render(self, context):
try:
self.user_id = template.resolve_variable(self.user_id,
context)
self.obj = template.resolve_variable(self.obj, context)
except template.VariableDoesNotExist:
return ''
ctype = ContentType.objects.get_for_model(obj)
if Bookmark.objects.filter(content_type=ctype,
object_id=
obj.id, user__pk=
user_id.id):
return self.nodelist_true.render(context)
else:
return self.nodelist_false.render(context)
def do_if_bookmarked(parser, token):
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes exactly two
arguments" % bits[0])
nodelist_true = parser.parse(('else', 'endif_bookmarked'))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse(('endif_bookmarked',))
parser.delete_first_token()
else:
nodelist_false = template.NodeList()
return IfBookmarkedNode(bits[1], bits[2], nodelist_true,
nodelist_false)
And this is the model it should be importing:
class Bookmark(models.Model):
"A bookmarked item, saved by a user with a timestamp"
# generic relation
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type',
'object_id')
# who and when
user = models.ForeignKey(User)
timestamp = models.DateTimeField(auto_now_add=True)
The bookmarking model works fine on its own, and I've gotten the
functions in the template tag to work in isolation in the interpreter,
but when I load the tag library it breaks the template. What am I
missing here?