This code allows you to call any view that returns with render_to_string via a tag like this: {% callview package.module1.module2.viewname arg1=value1 arg2=value2 ... %} The view's context will contain the arguments passed through the tag.
1 from django import template
2
3 register = template.Library()
4
5 @register.tag
6 def callview(parser, token):
7 bits = str(token.contents).split()
8 modulename, viewname = bits[1].rsplit('.', 1)
9 if len(bits) < 2:
10 raise TemplateSyntaxError, "callview tag takes at least 2 arguments"
11 module = __import__(modulename, globals(), locals(), [viewname])
12 view = getattr(module, viewname)
13 return CallViewNode(view, bits[2:])
14
15 class CallViewNode(template.Node):
16 def __init__(self, view, args):
17 self.view = view
18 self.args = args
19
20 def render(self, context):
21 for arg in self.args:
22 key, value = arg.split('=')
23 context[key] = value
24 return self.view(context)
original snippet from http://www.djangosnippets.org/snippets/109/
1 import cPickle as pickle
2 import md5
3
4 def cache_function(length):
5 """
6 A variant of the snippet posted by Jeff Wheeler at
7 http://www.djangosnippets.org/snippets/109/
8
9 Caches a function, using the function and its arguments as the key, and the return
10 value as the value saved. It passes all arguments on to the function, as
11 it should.
12
13 The decorator itself takes a length argument, which is the number of
14 seconds the cache will keep the result around.
15
16 It will put in a MethodNotFinishedError in the cache while the function is
17 processing. This should not matter in most cases, but if the app is using
18 threads, you won't be able to get the previous value, and will need to
19 wait until the function finishes. If this is not desired behavior, you can
20 remove the first two lines after the ``else``.
21 """
22 def decorator(func):
23 def inner_func(*args, **kwargs):
24 from django.core.cache import cache
25
26 raw = [func.__name__, func.__module__, args, kwargs]
27 pickled = pickle.dumps(raw, protocol=pickle.HIGHEST_PROTOCOL)
28 key = md5.new(pickled).hexdigest()
29 value = cache.get(key)
30 if cache.has_key(key):
31 return value
32 else:
33 # This will set a temporary value while ``func`` is being
34 # processed. When using threads, this is vital, as otherwise
35 # the function can be called several times before it finishes
36 # and is put into the cache.
37 class MethodNotFinishedError(Exception): pass
38 cache.set(key, MethodNotFinishedError(
39 'The function %s has not finished processing yet. This \
40 value will be replaced when it finishes.' % (func.__name__)
41 ), length)
42 result = func(*args, **kwargs)
43 cache.set(key, result, length)
44 return result
45 return inner_func
46 return decorator
Here is a quick snippet to configure a vhost for django with lighttpd and fastcgi. Website is launched with this command line : python manage.py runfcgi method=prefork socket=/tmp/yourproject.sock pidfile=/tmp/yourproject.id
1 $HTTP["host"] =~ "(^|\.)yourproject.com" {
2 server.document-root = "/path/toyourproject"
3
4 fastcgi.server = (
5 "/mysite.fcgi" => (
6 "main" => (
7 "socket" => "/tmp/yourproject.sock",
8 "check-local" => "disable",
9 )
10 ),
11 )
12
13 alias.url = (
14 "/media/" => "/path/toyourproject/media/",
15 )
16
17 url.rewrite-once = (
18 "^(/media.*)$" => "$1",
19 "^/favicon\.ico$" => "/media/favicon.ico",
20 "^(/.*)$" => "/mysite.fcgi$1",
21 )
22 }
get most used tags for a model. This is a code that should be add to manager.py of django-tagging (http://code.google.com/p/django-tagging/) extensions in TagManager class. It works only with trunk version.
1 def model_watch(self, Model, tagslimit=0):
2 model_table = qn(Model._meta.db_table)
3 model_pk = '%s.%s' % (model_table, qn(Model._meta.pk.column))
4 query = """
5 SELECT DISTINCT %(tag)s.id, %(tag)s.name, COUNT(%(model_pk)s) as count
6 FROM
7 %(tag)s
8 INNER JOIN %(tagged_item)s
9 ON %(tag)s.id = %(tagged_item)s.tag_id
10 INNER JOIN %(model)s
11 ON %(tagged_item)s.object_id = %(model_pk)s
12 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
13 GROUP BY %(tag)s.id, %(tag)s.name
14 ORDER BY count DESC, %(tag)s.name ASC%(limit_sql)s""" % {
15 'tag': qn(self.model._meta.db_table),
16 'tagged_item': qn(self._get_related_model_by_accessor('items')._meta.db_table),
17 'model': model_table,
18 'model_pk': model_pk,
19 'content_type_id': ContentType.objects.get_for_model(Model).id,
20 'limit_sql': tagslimit != 0 and (' LIMIT %s' % tagslimit) or ''
21 }
22
23 cursor = connection.cursor()
24 cursor.execute(query)
25 tags = []
26 t=None
27 for row in cursor.fetchall():
28 t = self.model(*row[:2])
29 t.count = row[2]
30 tags.append(t)
31
32 return tags
This is a templatetag for django. It allow you to cut a string at the end of a word or previous word.
1 from django import template
2 from django.template.defaultfilters import striptags
3 from django.utils.encoding import force_unicode
4
5 register = template.Library()
6 def substring(value, l):
7 """
8 filter to have n chars from start of a string
9 """
10
11 ending = (" ", ".", "\n", "!", "?", ",")
12
13 s=striptags(value)
14 if len(s) > l:
15 if s[0:l+1] not in ending:
16 c=""
17 i=l
18 while c!=" " and c!="\n" and i!=0:
19 i = i-1
20 c = s[i]
21 tmp = s[0:i]
22 if tmp=='':
23 return s[0:l] + "..."
24 else:
25 return tmp + '...'
26 else:
27 return force_unicode(s[0:l])
28 register.filter(substring)
Pages : 1