Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Removing the flat template_utils pluggable so it can be replaced.

  • Loading branch information...
commit dcf493379dfdc4a6d8373d2525b88b426f71e887 1 parent 1978d71
@bryanveloso bryanveloso authored
View
0  applications/template_utils/__init__.py
No changes.
View
32 applications/template_utils/context_processors.py
@@ -1,32 +0,0 @@
-"""
-A generic function for generating context processors, and a processor
-which adds media-specific settings to each ``RequestContext``.
-
-"""
-
-def settings_processor(*settings_list):
- """
- Generates and returns a context processor function which will read
- the values of all the settings passed in and return them in each
- ``RequestContext`` in which it is applied.
-
- For example::
-
- my_settings_processor = settings_processor('INTERNAL_IPS', 'SITE_ID')
-
- ``my_settings_processor`` would then be a valid context processor
- which would return the values of the settings ``INTERNAL_IPS`` and
- ``SITE_ID`` in each ``RequestContext`` in which it was applied.
-
- """
- def _processor(request):
- from django.conf import settings
- settings_dict = {}
- for setting_name in settings_list:
- settings_dict[setting_name] = getattr(settings, setting_name)
- return settings_dict
- return _processor
-
-media = settings_processor('ADMIN_MEDIA_PREFIX', 'MEDIA_URL')
-media.__doc__ = """A context processor which adds the values of the settings
-``ADMIN_MEDIA_PREFIX`` and ``MEDIA_URL`` to a ``RequestContext``."""
View
215 applications/template_utils/markup.py
@@ -1,215 +0,0 @@
-"""
-Utilities for text-to-HTML conversion.
-
-"""
-
-
-def textile(text, **kwargs):
- """
- Applies Textile conversion to a string, and returns the HTML.
-
- This is simply a pass-through to the ``textile`` template filter
- included in ``django.contrib.markup``, which works around issues
- PyTextile has with Unicode strings. If you're not using Django but
- want to use Textile with ``MarkupFormatter``, you'll need to
- supply your own Textile filter.
-
- """
- from django.contrib.markup.templatetags.markup import textile
- return textile(text)
-
-def markdown(text, **kwargs):
- """
- Applies Markdown conversion to a string, and returns the HTML.
-
- """
- import markdown
- return markdown.markdown(text, **kwargs)
-
-def restructuredtext(text, **kwargs):
- """
- Applies reStructuredText conversion to a string, and returns the
- HTML.
-
- """
- from docutils import core
- parts = core.publish_parts(source=text,
- writer_name='html4css1',
- **kwargs)
- return parts['fragment']
-
-DEFAULT_MARKUP_FILTERS = {
- 'textile': textile,
- 'markdown': markdown,
- 'restructuredtext': restructuredtext
- }
-
-
-class MarkupFormatter(object):
- """
- Generic markup formatter which can handle multiple text-to-HTML
- conversion systems.
-
-
- Overview
- ========
-
- Conversion is handled by filter functions registered with an
- instance; a set of default filters is provided which cover
- Markdown, reStructuredText and Textile (though using one of these
- requires the appropriate module to be available on your system --
- e.g., using the reST filter requires you to have ``docutils``
- installed).
-
- New filters can be added by registering them with an instance;
- simply define a function which performs the conversion you want,
- and use the ``register`` method to add it; ``register`` expects
- two arguments:
-
- 1. The name to associate with the filter.
-
- 2. The actual filter function.
-
- So, for example, you might define a new filter function called
- ``my_filter``, and register it like so::
-
- formatter = MarkupFormatter()
- formatter.register('my_filter', my_filter)
-
- Instances are callable, so applying the conversion to a string is
- simple::
-
- my_html = formatter(my_string, filter_name='my_filter')
-
- The filter to use for conversion is determined in either of two
- ways:
-
- 1. If the keyword argument ``filter_name`` is supplied, it will be
- used as the filter name.
-
- 2. Absent an explicit argument, the filter name will be taken from
- the ``MARKUP_FILTER`` setting in your Django settings file (see
- below).
-
- Additionally, arbitrary keyword arguments can be supplied, and
- they will be passed on to the filter function.
-
-
- Reading default bahavior from a Django setting
- ==============================================
-
- The Django setting ``MARKUP_FILTER`` can be used to specify
- default behavior; if used, its value should be a 2-tuple:
-
- * The first element should be the name of a filter.
-
- * The second element should be a dictionary to use as keyword
- arguments for that filter.
-
- So, for example, to have the default behavior apply Markdown with
- safe mode enabled, you would add this to your Django settings
- file::
-
- MARKUP_FILTER = ('markdown', { 'safe_mode': True })
-
- The filter named in this setting does not have to be from the
- default set; as long as you register a filter of that name before
- trying to use the formatter, it will work.
-
- To have the default behavior apply no conversion whatsoever, set
- ``MARKUP_FILTER`` like so::
-
- MARKUP_FILTER = (None, {})
-
- When the ``filter_name`` keyword argument is supplied, the
- ``MARKUP_FILTER`` setting is ignored entirely -- neither a filter
- name nor any keyword arguments will be read from it. This means
- that, by always supplying ``filter_name`` explicitly, it is
- possible to use this formatter without configuring or even
- installing Django.
-
-
- Django and template autoescaping
- ================================
-
- Django's template system defaults to escaping the output of
- template variables, which can interfere with functions intended to
- return HTML. ``MarkupFormatter`` does not in any way tamper with
- Django's autoescaping, so pasing the results of formatting
- directly to a Django template will result in that text being
- escaped.
-
- If you need to use ``MarkupFormatter`` for items which will be
- passed to a Django template as variables, use the function
- ``django.utils.safestring.mark_safe`` to tell Django's template
- system not to escape that text.
-
- For convenience, a Django template filter is included (in
- ``templatetags/generic_markup.py``) which applies
- ``MarkupFormatter`` to a string and marks the result as not
- requiring autoescaping.
-
-
- Examples
- ========
-
- Using the default behavior, with the filter name and arguments
- taken from the ``MARKUP_FILTER`` setting::
-
- formatter = MarkupFormatter()
- my_string = 'Lorem ipsum dolor sit amet.\n\nConsectetuer adipiscing elit.'
- my_html = formatter(my_string)
-
- Explicitly naming the filter to use::
-
- my_html = formatter(my_string, filter_name='markdown')
-
- Passing keyword arguments::
-
- my_html = formatter(my_string, filter_name='markdown', safe_mode=True)
-
- Perform no conversion (return the text as-is)::
-
- my_html = formatter(my_string, filter_name=None)
-
- """
- def __init__(self):
- self._filters = {}
- for filter_name, filter_func in DEFAULT_MARKUP_FILTERS.items():
- self.register(filter_name, filter_func)
-
- def register(self, filter_name, filter_func):
- """
- Registers a new filter for use.
-
- """
- self._filters[filter_name] = filter_func
-
- def __call__(self, text, **kwargs):
- """
- Applies text-to-HTML conversion to a string, and returns the
- HTML.
-
- """
- if 'filter_name' in kwargs:
- filter_name = kwargs['filter_name']
- del kwargs['filter_name']
- filter_kwargs = {}
- else:
- from django.conf import settings
- filter_name, filter_kwargs = settings.MARKUP_FILTER
- if filter_name is None:
- return text
- if filter_name not in self._filters:
- raise ValueError("'%s' is not a registered markup filter. Registered filters are: %s." % (filter_name,
- ', '.join(self._filters.iterkeys())))
- filter_func = self._filters[filter_name]
- filter_kwargs.update(**kwargs)
- return filter_func(text, **filter_kwargs)
-
-
-# Unless you need to have multiple instances of MarkupFormatter lying
-# around, or want to subclass it, the easiest way to use it is to
-# import this instance.
-
-formatter = MarkupFormatter()
View
72 applications/template_utils/nodes.py
@@ -1,72 +0,0 @@
-"""
-Subclass of ``template.Node`` for easy context updating.
-
-"""
-
-from django.db.models import get_model
-from django.conf import settings
-from django import template
-
-
-class ContextUpdatingNode(template.Node):
- """
- Node that updates the context with certain values.
-
- Subclasses should define ``get_content()``, which should return a
- dictionary to be added to the context.
-
- """
- def render(self, context):
- context.update(self.get_content(context))
- return ''
-
- def get_content(self, context):
- raise NotImplementedError
-
-
-class GenericContentNode(ContextUpdatingNode):
- """
- Base Node class for retrieving objects from any model.
-
- By itself, this class will retrieve a number of objects from a
- particular model (specified by an "app_name.model_name" string)
- and store them in a specified context variable (these are the
- ``num``, ``model`` and ``varname`` arguments to the constructor,
- respectively), but is also intended to be subclassed for
- customization.
-
- There are two ways to add extra bits to the eventual database
- lookup:
-
- 1. Add the setting ``GENERIC_CONTENT_LOOKUP_KWARGS`` to your
- settings file; this should be a dictionary whose keys are
- "app_name.model_name" strings corresponding to models, and whose
- values are dictionaries of keyword arguments which will be
- passed to ``filter()``.
-
- 2. Subclass and override ``_get_query_set``; all that's expected
- is that it will return a ``QuerySet`` which will be used to
- retrieve the object(s). The default ``QuerySet`` for the
- specified model (filtered as described above) will be available
- as ``self.query_set`` if you want to work with it.
-
- """
- def __init__(self, model, num, varname):
- self.num = num
- self.varname = varname
- lookup_dict = getattr(settings, 'GENERIC_CONTENT_LOOKUP_KWARGS', {})
- self.model = get_model(*model.split('.'))
- if self.model is None:
- raise template.TemplateSyntaxError("Generic content tag got invalid model: %s" % model)
- self.query_set = self.model._default_manager.filter(**lookup_dict.get(model, {}))
-
- def _get_query_set(self):
- return self.query_set
-
- def get_content(self, context):
- query_set = self._get_query_set()
- if self.num == 1:
- result = query_set[0]
- else:
- result = list(query_set[:self.num])
- return { self.varname: result }
View
0  applications/template_utils/templatetags/__init__.py
No changes.
View
87 applications/template_utils/templatetags/comparison.py
@@ -1,87 +0,0 @@
-"""
-Tags for performing basic value comparisons in templates.
-
-"""
-
-
-from django import template
-
-
-COMPARISON_DICT = {
- 'less': lambda x: x < 0,
- 'less_or_equal': lambda x: x <= 0,
- 'greater_or_equal': lambda x: x >= 0,
- 'greater': lambda x: x > 0,
- }
-
-
-class ComparisonNode(template.Node):
- def __init__(self, var1, var2, comparison, nodelist_true, nodelist_false):
- self.var1 = template.Variable(var1)
- self.var2 = template.Variable(var2)
- self.comparison = comparison
- self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
-
- def render(self, context):
- try:
- result = cmp(self.var1.resolve(context),
- self.var2.resolve(context))
- if COMPARISON_DICT[self.comparison](result):
- return self.nodelist_true.render(context)
- # If either variable fails to resolve, return nothing.
- except template.VariableDoesNotExist:
- return ''
- # If the types don't permit comparison, return nothing.
- except TypeError:
- return ''
- return self.nodelist_false.render(context)
-
-
-def do_comparison(parser, token):
- """
- Compares two values.
-
- Syntax::
-
- {% if_[comparison] [var1] [var2] %}
- ...
- {% else %}
- ...
- {% endif_[comparison] %}
-
- The {% else %} block is optional, and ``var1`` and ``var2`` may be
- variables or literal values.
-
- Supported comparisons are ``less``, ``less_or_equal``, ``greater``
- and ``greater_or_equal``.
-
- Examples::
-
- {% if_less some_object.id 3 %}
- <p>{{ some_object }} has an id less than 3.</p>
- {% endif_less %}
-
- {% if_greater_or_equal forloop.counter 4 %}
- <p>This is at least the fifth time through the loop.</p>
- {% else %}
- <p>This is one of the first four trips through the loop.</p>
- {% endif_greater_or_equal %}
-
- """
- bits = token.contents.split()
- if len(bits) != 3:
- raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
- end_tag = 'end' + bits[0]
- nodelist_true = parser.parse(('else', end_tag))
- token = parser.next_token()
- if token.contents == 'else':
- nodelist_false = parser.parse((end_tag,))
- parser.delete_first_token()
- else:
- nodelist_false = template.NodeList()
- comparison = bits[0].split('if_')[1]
- return ComparisonNode(bits[1], bits[2], comparison, nodelist_true, nodelist_false)
-
-register = template.Library()
-for tag_name in ('if_less', 'if_less_or_equal', 'if_greater_or_equal', 'if_greater'):
- register.tag(tag_name, do_comparison)
View
145 applications/template_utils/templatetags/feeds.py
@@ -1,145 +0,0 @@
-"""
-Tags which can retrieve and parse RSS and Atom feeds, and return the
-results for use in templates.
-
-Based, in part, on the original idea by user baumer1122 and posted to
-djangosnippets at http://www.djangosnippets.org/snippets/311/
-
-"""
-
-import datetime
-import feedparser
-from django import template
-from django.template.loader import render_to_string
-
-from template_utils.nodes import ContextUpdatingNode
-
-
-class FeedIncludeNode(template.Node):
- def __init__(self, feed_url, template_name, num_items=None):
- self.feed_url = template.Variable(feed_url)
- self.num_items = num_items
- self.template_name = template_name
-
- def render(self, context):
- feed_url = self.feed_url.resolve(context)
- feed = feedparser.parse(feed_url)
- items = []
- num_items = int(self.num_items) or len(feed['entries'])
- for i in range(num_items):
- pub_date = feed['entries'][i].updated_parsed
- published = datetime.date(pub_date[0], pub_date[1], pub_date[2])
- items.append({ 'title': feed['entries'][i].title,
- 'summary': feed['entries'][i].summary,
- 'link': feed['entries'][i].link,
- 'date': published })
- return render_to_string(self.template_name, { 'items': items,
- 'feed': feed })
-
-
-class FeedParserNode(ContextUpdatingNode):
- def __init__(self, feed_url, varname):
- self.feed_url = template.Variable(feed_url)
- self.varname = varname
-
- def get_content(self, context):
- feed_url = self.feed_url.resolve(context)
- return { self.varname: feedparser.parse(feed_url) }
-
-
-def do_include_feed(parser, token):
- """
- Parse an RSS or Atom feed and render a given number of its items
- into HTML.
-
- It is **highly** recommended that you use `Django's template
- fragment caching`_ to cache the output of this tag for a
- reasonable amount of time (e.g., one hour); polling a feed too
- often is impolite, wastes bandwidth and may lead to the feed
- provider banning your IP address.
-
- .. _Django's template fragment caching: http://www.djangoproject.com/documentation/cache/#template-fragment-caching
-
- Arguments should be:
-
- 1. The URL of the feed to parse.
-
- 2. The number of items to render (if not supplied, renders all
- items in the feed).
-
- 3. The name of a template to use for rendering the results into HTML.
-
- The template used to render the results will receive two variables:
-
- ``items``
- A list of dictionaries representing feed items, each with
- 'title', 'summary', 'link' and 'date' members.
-
- ``feed``
- The feed itself, for pulling out arbitrary attributes.
-
- Requires the Universal Feed Parser, which can be obtained at
- http://feedparser.org/. See `its documentation`_ for details of the
- parsed feed object.
-
- .. _its documentation: http://feedparser.org/docs/
-
- Syntax::
-
- {% include_feed [feed_url] [num_items] [template_name] %}
-
- Example::
-
- {% include_feed "http://www2.ljworld.com/rss/headlines/" 10 feed_includes/ljworld_headlines.html %}
-
- """
- bits = token.contents.split()
- if len(bits) == 3:
- return FeedIncludeNode(feed_url=bits[1], template_name=bits[2])
- elif len(bits) == 4:
- return FeedIncludeNode(feed_url=bits[1], num_items=bits[2], template_name=bits[3])
- else:
- raise template.TemplateSyntaxError("'%s' tag takes either two or three arguments" % bits[0])
-
-def do_parse_feed(parser, token):
- """
- Parses a given feed and returns the result in a given context
- variable.
-
- It is **highly** recommended that you use `Django's template
- fragment caching`_ to cache the output of this tag for a
- reasonable amount of time (e.g., one hour); polling a feed too
- often is impolite, wastes bandwidth and may lead to the feed
- provider banning your IP address.
-
- .. _Django's template fragment caching: http://www.djangoproject.com/documentation/cache/#template-fragment-caching
-
- Arguments should be:
-
- 1. The URL of the feed to parse.
-
- 2. The name of a context variable in which to return the result.
-
- Requires the Universal Feed Parser, which can be obtained at
- http://feedparser.org/. See `its documentation`_ for details of the
- parsed feed object.
-
- .. _its documentation: http://feedparser.org/docs/
-
- Syntax::
-
- {% parse_feed [feed_url] as [varname] %}
-
- Example::
-
- {% parse_feed "http://www2.ljworld.com/rss/headlines/" as ljworld_feed %}
-
- """
- bits = token.contents.split()
- if len(bits) != 4:
- raise template.TemplateSyntaxError(u"'%s' tag takes three arguments" % bits[0])
- return FeedParserNode(bits[1], bits[3])
-
-register = template.Library()
-register.tag('include_feed', do_include_feed)
-register.tag('parse_feed', do_parse_feed)
View
157 applications/template_utils/templatetags/generic_content.py
@@ -1,157 +0,0 @@
-"""
-Template tags which can do retrieval of content from any model.
-
-"""
-
-
-from django import template
-from django.db.models import get_model
-
-from template_utils.nodes import ContextUpdatingNode, GenericContentNode
-
-
-class RandomObjectsNode(GenericContentNode):
- """
- A subclass of ``GenericContentNode`` which overrides
- ``_get_query_set`` to apply random ordering.
-
- """
- def _get_query_set(self):
- return self.query_set.order_by('?')
-
-
-class RetrieveObjectNode(ContextUpdatingNode):
- """
- ``Node`` subclass which retrieves a single object -- by
- primary-key lookup -- from a given model.
-
- Because this is a primary-key lookup, it is assumed that no other
- filtering is needed; hence, the settings-based filtering performed
- by ``GenericContentNode`` is not used here.
-
- """
- def __init__(self, model, pk, varname):
- self.pk = template.Variable(pk)
- self.varname = varname
- self.model = get_model(*model.split('.'))
- if self.model is None:
- raise template.TemplateSyntaxError("Generic content tag got invalid model: %s" % model)
-
- def get_content(self, context):
- return { self.varname: self.model._default_manager.get(pk=self.pk.resolve(context))}
-
-
-def do_latest_object(parser, token):
- """
- Retrieves the latest object from a given model, in that model's
- default ordering, and stores it in a context variable.
-
- Syntax::
-
- {% get_latest_object [app_name].[model_name] as [varname] %}
-
- Example::
-
- {% get_latest_object comments.freecomment as latest_comment %}
-
- """
- bits = token.contents.split()
- if len(bits) != 4:
- raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
- if bits [2] != 'as':
- raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
- return GenericContentNode(bits[1], 1, bits[3])
-
-
-def do_latest_objects(parser, token):
- """
- Retrieves the latest ``num`` objects from a given model, in that
- model's default ordering, and stores them in a context variable.
-
- Syntax::
-
- {% get_latest_objects [app_name].[model_name] [num] as [varname] %}
-
- Example::
-
- {% get_latest_objects comments.freecomment 5 as latest_comments %}
-
- """
- bits = token.contents.split()
- if len(bits) != 5:
- raise template.TemplateSyntaxError("'%s' tag takes four arguments" % bits[0])
- if bits [3] != 'as':
- raise template.TemplateSyntaxError("third argument to '%s' tag must be 'as'" % bits[0])
- return GenericContentNode(bits[1], bits[2], bits[4])
-
-def do_random_object(parser, token):
- """
- Retrieves a random object from a given model, and stores it in a
- context variable.
-
- Syntax::
-
- {% get_random_object [app_name].[model_name] as [varname] %}
-
- Example::
-
- {% get_random_object comments.freecomment as random_comment %}
-
- """
- bits = token.contents.split()
- if len(bits) != 4:
- raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
- if bits [2] != 'as':
- raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
- return RandomObjectsNode(bits[1], 1, bits[3])
-
-
-def do_random_objects(parser, token):
- """
- Retrieves ``num`` random objects from a given model, and stores
- them in a context variable.
-
- Syntax::
-
- {% get_random_objects [app_name].[model_name] [num] as [varname] %}
-
- Example::
-
- {% get_random_objects comments.freecomment 5 as random_comments %}
-
- """
- bits = token.contents.split()
- if len(bits) != 5:
- raise template.TemplateSyntaxError("'%s' tag takes four arguments" % bits[0])
- if bits [3] != 'as':
- raise template.TemplateSyntaxError("third argument to '%s' tag must be 'as'" % bits[0])
- return RandomObjectsNode(bits[1], bits[2], bits[4])
-
-
-def do_retrieve_object(parser, token):
- """
- Retrieves a specific object from a given model by primary-key
- lookup, and stores it in a context variable.
-
- Syntax::
-
- {% retrieve_object [app_name].[model_name] [pk] as [varname] %}
-
- Example::
-
- {% retrieve_object flatpages.flatpage 12 as my_flat_page %}
-
- """
- bits = token.contents.split()
- if len(bits) != 5:
- raise template.TemplateSyntaxError("'%s' tag takes four arguments" % bits[0])
- if bits[3] != 'as':
- raise template.TemplateSyntaxError("third argument to '%s' tag must be 'as'" % bits[0])
- return RetrieveObjectNode(bits[1], bits[2], bits[4])
-
-register = template.Library()
-register.tag('get_latest_object', do_latest_object)
-register.tag('get_latest_objects', do_latest_objects)
-register.tag('get_random_object', do_random_object)
-register.tag('get_random_objects', do_random_objects)
-register.tag('retrieve_object', do_retrieve_object)
View
47 applications/template_utils/templatetags/generic_markup.py
@@ -1,47 +0,0 @@
-"""
-Filters for converting plain text to HTML and enhancing the
-typographic appeal of text on the Web.
-
-"""
-
-
-from django.conf import settings
-from django.template import Library
-from django.utils.safestring import mark_safe
-
-from template_utils.markup import formatter
-
-
-def apply_markup(value, arg=None):
- """
- Applies text-to-HTML conversion.
-
- Takes an optional argument to specify the name of a filter to use.
-
- """
- if arg is not None:
- return mark_safe(formatter(value, filter_name=arg))
- return formatter(value)
-apply_markup.is_safe = True
-
-def smartypants(value):
- """
- Applies SmartyPants to a piece of text, applying typographic
- niceties.
-
- Requires the Python SmartyPants library to be installed; see
- http://web.chad.org/projects/smartypants.py/
-
- """
- try:
- from smartypants import smartyPants
- except ImportError:
- if settings.DEBUG:
- raise template.TemplateSyntaxError("Error in smartypants filter: the Python smartypants module is not installed or could not be imported")
- return value
- else:
- return smartyPants(value)
-
-register = Library()
-register.filter(apply_markup)
-register.filter(smartypants)
View
11 manage.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+from django.core.management import execute_manager
+try:
+ import settings # Assumed to be in the same directory.
+except ImportError:
+ import sys
+ sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ execute_manager(settings)
Please sign in to comment.
Something went wrong with that request. Please try again.