Author: floguy
Date: Sun Oct  5 17:59:34 2008
New Revision: 43

Modified:
    trunk/things/options.py
    trunk/things/templatetags/things_tags.py

Log:
Changes required to make ThingGroup usable in a real-world project.

Modified: trunk/things/options.py
==============================================================================
--- trunk/things/options.py     (original)
+++ trunk/things/options.py     Sun Oct  5 17:59:34 2008
@@ -50,7 +50,7 @@

      def list_view(self, request, descending=False, field=None,
          template_object_name='objects', template_name=None,
-        extra_context = {}, **kwargs):
+        extra_context = {}, templates=[], **kwargs):
          if template_name is None:
              template_name = self.list_template_name
          items = self.get_query_set()
@@ -80,8 +80,9 @@
                  items = items.order_by('%s%s' % (pre,  
field.get_aggregate_name()))
              else:
                  items = items.order_by('%s%s' % (pre, field.field_name))
-        templates = ['%s/%s' % (self.template_dir, template_name,),
-            '%s/list.html' % self.template_dir, 'things/list.html']
+        if not templates:
+            templates = ['%s/%s' % (self.template_dir, template_name,),
+                '%s/list.html' % self.template_dir, 'things/list.html']
          context = {
              template_object_name: items,
              'fields': self.fields.values(),
@@ -175,6 +176,17 @@
          qs = model._default_manager.all()
          super(ModelThing, self).__init__(qs)

+class GroupDict(dict):
+    def __init__(self, parent, *args, **kwargs):
+        self.parent = parent
+        super(GroupDict, self).__init__(*args, **kwargs)
+
+    def url(self):
+        return reverse(
+            '%s_list' % self.parent.name_prefix,
+            kwargs={'url_prefix': '%s/' % self['url_name']}
+        )
+
  class ThingGroup(object):
      """
      [
@@ -195,13 +207,17 @@
          if not group_dicts and not group_func:
              raise TypeError("Either group_dicts or group_func must be  
specified.")
          if group_dicts:
-            self.groups = group_dicts
+            groups = group_dicts
          else:
-            self.groups = group_func(thing)
-        for group in self.groups:
+            groups = group_func(thing)
+
+        self.groups = []
+        for group in groups:
              for key in ('queryset', 'name', 'url_name'):
                  if key not in group:
                      raise TypeError("Group dictionary must include a '%s'  
argument." % key)
+            self.groups.append(GroupDict(self, group))
+
          self.thing = thing

      def urls(self, prefix='^', name_prefix='things', url_prefix='',
@@ -228,25 +244,22 @@
              tmp_urls.extend(thing.urls(
                  prefix='%s%s' % (prefix, self.url_prefix, ),
                  extra_context=context,
-                name_prefix="%s_%s" % (name_prefix, group['url_name']),
+                name_prefix=name_prefix,
                  url_prefix='%s/' % group['url_name'],
              ))
          return patterns('', *tmp_urls)

      def group_view(self, request, extra_context={}, url_prefix=None):
+        context = {
+            'groups': self.groups,
+        }
+        context.update(extra_context)
          if self.template_name is None:
              template_name = '%s_groups.html' % (self.__class__.__name__,)
          else:
              template_name = self.template_name
          templates = ['%s/%s' % (self.template_dir, template_name,),
              '%s/groups.html' % self.template_dir, 'things/groups.html']
-        groups = self.groups
-        for group in groups:
-            group['url'] = reverse('%s_%s_list' % (self.name_prefix,  
group['url_name']), kwargs={'url_prefix': '%s/' % group['url_name']})
-        context = {
-            'groups': groups,
-        }
-        context.update(extra_context)
          t = select_template(templates)
          c = RequestContext(request, context)
          return HttpResponse(t.render(c))

Modified: trunk/things/templatetags/things_tags.py
==============================================================================
--- trunk/things/templatetags/things_tags.py    (original)
+++ trunk/things/templatetags/things_tags.py    Sun Oct  5 17:59:34 2008
@@ -1,5 +1,5 @@
  from django import template
-from django.core.urlresolvers import reverse
+from django.core.urlresolvers import reverse, NoReverseMatch

  register = template.Library()

@@ -45,4 +45,69 @@
          'terms': context['terms'],
          'request': context['request'],
      }
-register.inclusion_tag('things/search.html',  
takes_context=True)(display_search)
\ No newline at end of file
+register.inclusion_tag('things/search.html',  
takes_context=True)(display_search)
+
+def do_urlslash(parser, token):
+    bits = token.contents.split(' ')
+    if len(bits) < 2:
+        raise TemplateSyntaxError("'%s' takes at least one argument"
+                                  " (path to a view)" % bits[0])
+    viewname = bits[1]
+    args = []
+    kwargs = {}
+    asvar = None
+
+    if len(bits) > 2:
+        bits = iter(bits[2:])
+        for bit in bits:
+            if bit == 'as':
+                asvar = bits.next()
+                break
+            else:
+                for arg in bit.split(","):
+                    if '=' in arg:
+                        k, v = arg.split('=', 1)
+                        k = k.strip()
+                        kwargs[k] = parser.compile_filter(v)
+                    elif arg:
+                        args.append(parser.compile_filter(arg))
+    return URLSlashNode(viewname, args, kwargs, asvar)
+
+class URLSlashNode(template.Node):
+    def __init__(self, view_name, args, kwargs, asvar):
+        self.view_name = view_name
+        self.args = args
+        self.kwargs = kwargs
+        self.asvar = asvar
+
+    def render(self, context):
+        args = [arg.resolve(context) for arg in self.args]
+        kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
+                       for k, v in self.kwargs.items()])
+
+
+        # Try to look up the URL twice: once given the view name, and again
+        # relative to what we guess is the "main" app. If they both fail,
+        # re-raise the NoReverseMatch unless we're using the
+        # {% url ... as var %} construct in which cause return nothing.
+        url = ''
+        try:
+            args = ['%s/' % a for a in args]
+            kwargs = dict((k, '%s/' % v) for k, v in kwargs.iteritems())
+            url = reverse(self.view_name, args=args, kwargs=kwargs)
+        except NoReverseMatch:
+            project_name = settings.SETTINGS_MODULE.split('.')[0]
+            try:
+                url = reverse(project_name + '.' + self.view_name,
+                              args=args, kwargs=kwargs)
+            except NoReverseMatch:
+                if self.asvar is None:
+                    raise
+
+        if self.asvar:
+            context[self.asvar] = url
+            return ''
+        else:
+            return url
+
+register.tag('urlslash', do_urlslash)
\ No newline at end of file

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"pinax-updates" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pinax-updates?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to