Merge branch 'develop' of git://github.com/melinath/philo into develop
authorJoseph Spiros <joseph.spiros@ithinksw.com>
Wed, 22 Jun 2011 17:07:51 +0000 (13:07 -0400)
committerJoseph Spiros <joseph.spiros@ithinksw.com>
Wed, 22 Jun 2011 17:07:51 +0000 (13:07 -0400)
* 'develop' of git://github.com/melinath/philo:
  Added winer doc file. Improved the docstrings for FeedView from the penfield version.
  Renamed syndication to winer.
  Added information about request context processor to shipherd docs. See issue #160.
  Minor correction to shipherd howto.
  Moved a migration after the master migrations.
  Tweaked FeedView to more correctly generate links vs feed urls.
  Improved penfield docstrings. Added urlpatterns and support for all registered feed types. Resolves issue #141.
  Initial implementation of a separate syndication contrib app based on penfield's FeedView, updated to use a registry instead of a dict.
  Moved sobol's search registry into core as a generic registry utility. Added support for RegistryIterators directly to SlugMultipleChoiceField since it is a common use case.
  Made views optional on nodes; nodes without views will raise a 404 when rendering and will return False for accepting and handling subpaths. Implements feature #131.

20 files changed:
docs/contrib/intro.rst
docs/contrib/penfield.rst
docs/contrib/winer.rst [new file with mode: 0644]
docs/tutorials/shipherd.rst
philo/contrib/__init__.py
philo/contrib/julian/models.py
philo/contrib/penfield/exceptions.py [deleted file]
philo/contrib/penfield/models.py
philo/contrib/shipherd/templatetags/shipherd.py
philo/contrib/sobol/models.py
philo/contrib/sobol/search.py
philo/contrib/winer/__init__.py [new file with mode: 0644]
philo/contrib/winer/exceptions.py [new file with mode: 0644]
philo/contrib/winer/feeds.py [new file with mode: 0644]
philo/contrib/winer/middleware.py [moved from philo/contrib/penfield/middleware.py with 58% similarity]
philo/contrib/winer/models.py [new file with mode: 0644]
philo/migrations/0018_auto__chg_field_node_view_object_id__chg_field_node_view_content_type.py [new file with mode: 0644]
philo/models/fields/__init__.py
philo/models/nodes.py
philo/utils/registry.py [new file with mode: 0644]

index 3b97ecd..e833317 100644 (file)
@@ -9,5 +9,6 @@ Contrib apps
        shipherd
        sobol
        waldo
+       winer
 
 .. automodule:: philo.contrib
index d774dcb..87073b9 100644 (file)
@@ -27,18 +27,6 @@ Newsletters
 .. autoclass:: philo.contrib.penfield.models.NewsletterView
        :members:
 
-Abstract Syndication
-++++++++++++++++++++
-
-.. autoclass:: philo.contrib.penfield.models.FeedView
-       :members:
-
-.. automodule:: philo.contrib.penfield.exceptions
-       :members:
-
-.. automodule:: philo.contrib.penfield.middleware
-       :members:
-
 Template filters
 ++++++++++++++++
 
diff --git a/docs/contrib/winer.rst b/docs/contrib/winer.rst
new file mode 100644 (file)
index 0000000..4b8a670
--- /dev/null
@@ -0,0 +1,15 @@
+Winer
+=====
+
+.. automodule:: philo.contrib.winer
+
+.. automodule:: philo.contrib.winer.models
+
+       .. autoclass:: FeedView
+               :members:
+
+.. automodule:: philo.contrib.winer.exceptions
+       :members:
+
+.. automodule:: philo.contrib.winer.middleware
+       :members:
\ No newline at end of file
index 3a62cb0..3454ef2 100644 (file)
@@ -3,7 +3,21 @@ Using Shipherd in the Admin
 
 The navigation mechanism is fairly complex; unfortunately, there's no real way around that - without a lot of equally complex code that you are quite welcome to write and contribute! ;-)
 
-For this guide, we'll assume that you have the setup described in :doc:`getting-started`. We'll be adding a main :class:`.Navigation` to the root :class:`.Node` and making it display as part of the :class:`.Template`. Before getting started, make sure that you've added :mod:`philo.contrib.shipherd` to your :setting:`INSTALLED_APPS`.
+For this guide, we'll assume that you have the setup described in :doc:`getting-started`. We'll be adding a main :class:`.Navigation` to the root :class:`.Node` and making it display as part of the :class:`.Template`.
+
+Before getting started, make sure that you've added :mod:`philo.contrib.shipherd` to your :setting:`INSTALLED_APPS`. :mod:`~philo.contrib.shipherd` template tags also require the request context processor, so make sure to set :setting:`TEMPLATE_CONTEXT_PROCESSORS` appropriately::
+
+       TEMPLATE_CONTEXT_PROCESSORS = (
+               # Defaults
+               "django.contrib.auth.context_processors.auth",
+               "django.core.context_processors.debug",
+               "django.core.context_processors.i18n",
+               "django.core.context_processors.media",
+               "django.core.context_processors.static",
+               "django.contrib.messages.context_processors.messages"
+               ...
+               "django.core.context_processors.request"
+       )
 
 Creating the Navigation
 +++++++++++++++++++++++
@@ -19,7 +33,7 @@ Displaying the Navigation
 
 All you need to do now is show the navigation in the template! This is quite easy, using the :ttag:`~philo.contrib.shipherd.templatetags.shipherd.recursenavigation` templatetag. For now we'll keep it simple. Adjust the "Hello World Template" to look like this::
        
-       <html>
+       <html>{% load shipherd %}
            <head>
                <title>{% container page_title %}</title>
            </head>
@@ -29,7 +43,7 @@ All you need to do now is show the navigation in the template! This is quite eas
                        <li{% if navloop.active %} class="active"{% endif %}>
                            {{ item.text }}
                        </li>
-                   {% endnavigation %}
+                   {% endrecursenavigation %}
                </ul>
                {% container page_body as content %}
                {% if content %}
index d6c4be4..0cde6d5 100644 (file)
@@ -2,9 +2,10 @@
 """
 Following Python and Django’s “batteries included” philosophy, Philo includes a number of optional packages that simplify common website structures:
 
-* :mod:`~philo.contrib.penfield` — Basic philo syndication, and blog and newsletter management.
+* :mod:`~philo.contrib.penfield` — Basic blog and newsletter management.
 * :mod:`~philo.contrib.shipherd` — Powerful site navigation.
 * :mod:`~philo.contrib.sobol` — Custom web and database searches.
 * :mod:`~philo.contrib.waldo` — Custom authentication systems.
+* :mod:`~philo.contrib.winer` — Abstract framework for Philo-based syndication.
 
 """
\ No newline at end of file
index 62b938a..e4e78ba 100644 (file)
@@ -15,7 +15,8 @@ from django.http import HttpResponse, Http404
 from django.utils.encoding import force_unicode
 
 from philo.contrib.julian.feedgenerator import ICalendarFeed
-from philo.contrib.penfield.models import FeedView, FEEDS
+from philo.contrib.winer.models import FeedView
+from philo.contrib.winer.feeds import registry
 from philo.exceptions import ViewCanNotProvideSubpath
 from philo.models import Tag, Entity, Page
 from philo.models.fields import TemplateField
@@ -25,8 +26,7 @@ from philo.utils import ContentTypeRegistryLimiter
 __all__ = ('register_location_model', 'unregister_location_model', 'Location', 'TimedModel', 'Event', 'Calendar', 'CalendarView',)
 
 
-ICALENDAR = ICalendarFeed.mime_type
-FEEDS[ICALENDAR] = ICalendarFeed
+registry.register(ICalendarFeed, verbose_name="iCalendar")
 try:
        DEFAULT_SITE = Site.objects.get_current()
 except:
@@ -461,5 +461,4 @@ class CalendarView(FeedView):
                return u"%s for %s" % (self.__class__.__name__, self.calendar)
 
 field = CalendarView._meta.get_field('feed_type')
-field._choices += ((ICALENDAR, 'iCalendar'),)
-field.default = ICALENDAR
\ No newline at end of file
+field.default = registry.get_slug(ICalendarFeed, field.default)
\ No newline at end of file
diff --git a/philo/contrib/penfield/exceptions.py b/philo/contrib/penfield/exceptions.py
deleted file mode 100644 (file)
index 96b96ed..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-class HttpNotAcceptable(Exception):
-       """This will be raised if an Http-Accept header will not accept the feed content types that are available."""
-       pass
\ No newline at end of file
index 3632ff6..3a8e82f 100644 (file)
@@ -2,327 +2,15 @@ from datetime import date, datetime
 
 from django.conf import settings
 from django.conf.urls.defaults import url, patterns, include
-from django.contrib.sites.models import Site, RequestSite
-from django.contrib.syndication.views import add_domain
 from django.db import models
 from django.http import Http404, HttpResponse
-from django.template import RequestContext, Template as DjangoTemplate
-from django.utils import feedgenerator, tzinfo
-from django.utils.datastructures import SortedDict
-from django.utils.encoding import smart_unicode, force_unicode
-from django.utils.html import escape
 
-from philo.contrib.penfield.exceptions import HttpNotAcceptable
-from philo.contrib.penfield.middleware import http_not_acceptable
+from philo.contrib.winer.models import FeedView
 from philo.exceptions import ViewCanNotProvideSubpath
-from philo.models import Tag, Entity, MultiView, Page, register_value_model, Template
+from philo.models import Tag, Entity, Page, register_value_model
 from philo.models.fields import TemplateField
 from philo.utils import paginate
 
-try:
-       import mimeparse
-except:
-       mimeparse = None
-
-
-ATOM = feedgenerator.Atom1Feed.mime_type
-RSS = feedgenerator.Rss201rev2Feed.mime_type
-FEEDS = SortedDict([
-       (ATOM, feedgenerator.Atom1Feed),
-       (RSS, feedgenerator.Rss201rev2Feed),
-])
-FEED_CHOICES = (
-       (ATOM, "Atom"),
-       (RSS, "RSS"),
-)
-
-
-class FeedView(MultiView):
-       """
-       :class:`FeedView` handles a number of pages and related feeds for a single object such as a blog or newsletter. In addition to all other methods and attributes, :class:`FeedView` supports the same generic API as `django.contrib.syndication.views.Feed <http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#django.contrib.syndication.django.contrib.syndication.views.Feed>`_.
-       
-       """
-       #: The type of feed which should be served by the :class:`FeedView`.
-       feed_type = models.CharField(max_length=50, choices=FEED_CHOICES, default=ATOM)
-       #: The suffix which will be appended to a page URL for a feed of its items. Default: "feed"
-       feed_suffix = models.CharField(max_length=255, blank=False, default="feed")
-       #: A :class:`BooleanField` - whether or not feeds are enabled.
-       feeds_enabled = models.BooleanField(default=True)
-       #: A :class:`PositiveIntegerField` - the maximum number of items to return for this feed. All items will be returned if this field is blank. Default: 15.
-       feed_length = models.PositiveIntegerField(blank=True, null=True, default=15, help_text="The maximum number of items to return for this feed. All items will be returned if this field is blank.")
-       
-       #: A :class:`ForeignKey` to a :class:`.Template` which will be used to render the title of each item in the feed if provided.
-       item_title_template = models.ForeignKey(Template, blank=True, null=True, related_name="%(app_label)s_%(class)s_title_related")
-       #: A :class:`ForeignKey` to a :class:`.Template` which will be used to render the description of each item in the feed if provided.
-       item_description_template = models.ForeignKey(Template, blank=True, null=True, related_name="%(app_label)s_%(class)s_description_related")
-       
-       #: The name of the context variable to be populated with the items managed by the :class:`FeedView`.
-       item_context_var = 'items'
-       #: The attribute on a subclass of :class:`FeedView` which will contain the main object of a feed (such as a :class:`Blog`.)
-       object_attr = 'object'
-       
-       #: A description of the feeds served by the :class:`FeedView`. This is a required part of the :class:`django.contrib.syndication.view.Feed` API.
-       description = ""
-       
-       def feed_patterns(self, base, get_items_attr, page_attr, reverse_name):
-               """
-               Given the name to be used to reverse this view and the names of the attributes for the function that fetches the objects, returns patterns suitable for inclusion in urlpatterns.
-               
-               :param base: The base of the returned patterns - that is, the subpath pattern which will reference the page for the items. The :attr:`feed_suffix` will be appended to this subpath.
-               :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` which will return an (``items``, ``extra_context``) tuple. This will be passed directly to :meth:`feed_view` and :meth:`page_view`.
-               :param page_attr: A :class:`.Page` instance or the name of an attribute on the :class:`FeedView` which contains a :class:`.Page` instance. This will be passed directly to :meth:`page_view` and will be rendered with the items from ``get_items_attr``.
-               :param reverse_name: The string which is considered the "name" of the view function returned by :meth:`page_view` for the given parameters.
-               :returns: Patterns suitable for use in urlpatterns.
-               
-               Example::
-               
-                       @property
-                       def urlpatterns(self):
-                               urlpatterns = self.feed_patterns(r'^', 'get_all_entries', 'index_page', 'index')
-                               urlpatterns += self.feed_patterns(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})', 'get_entries_by_ymd', 'entry_archive_page', 'entries_by_day')
-                               return urlpatterns
-               
-               """
-               urlpatterns = patterns('')
-               if self.feeds_enabled:
-                       feed_reverse_name = "%s_feed" % reverse_name
-                       feed_view = http_not_acceptable(self.feed_view(get_items_attr, feed_reverse_name))
-                       feed_pattern = r'%s%s%s$' % (base, (base and base[-1] != "^") and "/" or "", self.feed_suffix)
-                       urlpatterns += patterns('',
-                               url(feed_pattern, feed_view, name=feed_reverse_name),
-                       )
-               urlpatterns += patterns('',
-                       url(r"%s$" % base, self.page_view(get_items_attr, page_attr), name=reverse_name)
-               )
-               return urlpatterns
-       
-       def get_object(self, request, **kwargs):
-               """By default, returns the object stored in the attribute named by :attr:`object_attr`. This can be overridden for subclasses that publish different data for different URL parameters. It is part of the :class:`django.contrib.syndication.views.Feed` API."""
-               return getattr(self, self.object_attr)
-       
-       def feed_view(self, get_items_attr, reverse_name):
-               """
-               Returns a view function that renders a list of items as a feed.
-               
-               :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` that will return a (items, extra_context) tuple when called with view arguments.
-               :param reverse_name: The name which can be used reverse this feed using the :class:`FeedView` as the urlconf.
-               
-               :returns: A view function that renders a list of items as a feed.
-               
-               """
-               get_items = callable(get_items_attr) and get_items_attr or getattr(self, get_items_attr)
-               
-               def inner(request, extra_context=None, *args, **kwargs):
-                       obj = self.get_object(request, *args, **kwargs)
-                       feed = self.get_feed(obj, request, reverse_name)
-                       items, xxx = get_items(request, extra_context=extra_context, *args, **kwargs)
-                       self.populate_feed(feed, items, request)
-                       
-                       response = HttpResponse(mimetype=feed.mime_type)
-                       feed.write(response, 'utf-8')
-                       return response
-               
-               return inner
-       
-       def page_view(self, get_items_attr, page_attr):
-               """
-               :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` that will return a (items, extra_context) tuple when called with view arguments.
-               :param page_attr: A :class:`.Page` instance or the name of an attribute on the :class:`FeedView` which contains a :class:`.Page` instance. This will be rendered with the items from ``get_items_attr``.
-               
-               :returns: A view function that renders a list of items as an :class:`HttpResponse`.
-               
-               """
-               get_items = callable(get_items_attr) and get_items_attr or getattr(self, get_items_attr)
-               page = isinstance(page_attr, Page) and page_attr or getattr(self, page_attr)
-               
-               def inner(request, extra_context=None, *args, **kwargs):
-                       items, extra_context = get_items(request, extra_context=extra_context, *args, **kwargs)
-                       items, item_context = self.process_page_items(request, items)
-                       
-                       context = self.get_context()
-                       context.update(extra_context or {})
-                       context.update(item_context or {})
-                       
-                       return page.render_to_response(request, extra_context=context)
-               return inner
-       
-       def process_page_items(self, request, items):
-               """
-               Hook for handling any extra processing of ``items`` based on an :class:`HttpRequest`, such as pagination or searching. This method is expected to return a list of items and a dictionary to be added to the page context.
-               
-               """
-               item_context = {
-                       self.item_context_var: items
-               }
-               return items, item_context
-       
-       def get_feed_type(self, request):
-               """
-               Intelligently chooses a feed type for a given request. Tries to return :attr:`feed_type`, but if the Accept header does not include that mimetype, tries to return the best match from the feed types that are offered by the :class:`FeedView`. If none of the offered feed types are accepted by the :class:`HttpRequest`, then this method will raise :exc:`philo.contrib.penfield.exceptions.HttpNotAcceptable`.
-               
-               """
-               feed_type = self.feed_type
-               if feed_type not in FEEDS:
-                       feed_type = FEEDS.keys()[0]
-               accept = request.META.get('HTTP_ACCEPT')
-               if accept and feed_type not in accept and "*/*" not in accept and "%s/*" % feed_type.split("/")[0] not in accept:
-                       # Wups! They aren't accepting the chosen format. Is there another format we can use?
-                       if mimeparse:
-                               feed_type = mimeparse.best_match(FEEDS.keys(), accept)
-                       else:
-                               for feed_type in FEEDS.keys():
-                                       if feed_type in accept or "%s/*" % feed_type.split("/")[0] in accept:
-                                               break
-                               else:
-                                       feed_type = None
-                       if not feed_type:
-                               raise HttpNotAcceptable
-               return FEEDS[feed_type]
-       
-       def get_feed(self, obj, request, reverse_name):
-               """
-               Returns an unpopulated :class:`django.utils.feedgenerator.DefaultFeed` object for this object.
-               
-               """
-               try:
-                       current_site = Site.objects.get_current()
-               except Site.DoesNotExist:
-                       current_site = RequestSite(request)
-               
-               feed_type = self.get_feed_type(request)
-               node = request.node
-               link = node.get_absolute_url(with_domain=True, request=request, secure=request.is_secure())
-               
-               feed = feed_type(
-                       title = self.__get_dynamic_attr('title', obj),
-                       subtitle = self.__get_dynamic_attr('subtitle', obj),
-                       link = link,
-                       description = self.__get_dynamic_attr('description', obj),
-                       language = settings.LANGUAGE_CODE.decode(),
-                       feed_url = add_domain(
-                               current_site.domain,
-                               self.__get_dynamic_attr('feed_url', obj) or node.construct_url(node._subpath, with_domain=True, request=request, secure=request.is_secure()),
-                               request.is_secure()
-                       ),
-                       author_name = self.__get_dynamic_attr('author_name', obj),
-                       author_link = self.__get_dynamic_attr('author_link', obj),
-                       author_email = self.__get_dynamic_attr('author_email', obj),
-                       categories = self.__get_dynamic_attr('categories', obj),
-                       feed_copyright = self.__get_dynamic_attr('feed_copyright', obj),
-                       feed_guid = self.__get_dynamic_attr('feed_guid', obj),
-                       ttl = self.__get_dynamic_attr('ttl', obj),
-                       **self.feed_extra_kwargs(obj)
-               )
-               return feed
-       
-       def populate_feed(self, feed, items, request):
-               """Populates a :class:`django.utils.feedgenerator.DefaultFeed` instance as is returned by :meth:`get_feed` with the passed-in ``items``."""
-               if self.item_title_template:
-                       title_template = DjangoTemplate(self.item_title_template.code)
-               else:
-                       title_template = None
-               if self.item_description_template:
-                       description_template = DjangoTemplate(self.item_description_template.code)
-               else:
-                       description_template = None
-               
-               node = request.node
-               try:
-                       current_site = Site.objects.get_current()
-               except Site.DoesNotExist:
-                       current_site = RequestSite(request)
-               
-               if self.feed_length is not None:
-                       items = items[:self.feed_length]
-               
-               for item in items:
-                       if title_template is not None:
-                               title = title_template.render(RequestContext(request, {'obj': item}))
-                       else:
-                               title = self.__get_dynamic_attr('item_title', item)
-                       if description_template is not None:
-                               description = description_template.render(RequestContext(request, {'obj': item}))
-                       else:
-                               description = self.__get_dynamic_attr('item_description', item)
-                       
-                       link = node.construct_url(self.reverse(obj=item), with_domain=True, request=request, secure=request.is_secure())
-                       
-                       enc = None
-                       enc_url = self.__get_dynamic_attr('item_enclosure_url', item)
-                       if enc_url:
-                               enc = feedgenerator.Enclosure(
-                                       url = smart_unicode(add_domain(
-                                                       current_site.domain,
-                                                       enc_url,
-                                                       request.is_secure()
-                                       )),
-                                       length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)),
-                                       mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item))
-                               )
-                       author_name = self.__get_dynamic_attr('item_author_name', item)
-                       if author_name is not None:
-                               author_email = self.__get_dynamic_attr('item_author_email', item)
-                               author_link = self.__get_dynamic_attr('item_author_link', item)
-                       else:
-                               author_email = author_link = None
-                       
-                       pubdate = self.__get_dynamic_attr('item_pubdate', item)
-                       if pubdate and not pubdate.tzinfo:
-                               ltz = tzinfo.LocalTimezone(pubdate)
-                               pubdate = pubdate.replace(tzinfo=ltz)
-                       
-                       feed.add_item(
-                               title = title,
-                               link = link,
-                               description = description,
-                               unique_id = self.__get_dynamic_attr('item_guid', item, link),
-                               enclosure = enc,
-                               pubdate = pubdate,
-                               author_name = author_name,
-                               author_email = author_email,
-                               author_link = author_link,
-                               categories = self.__get_dynamic_attr('item_categories', item),
-                               item_copyright = self.__get_dynamic_attr('item_copyright', item),
-                               **self.item_extra_kwargs(item)
-                       )
-       
-       def __get_dynamic_attr(self, attname, obj, default=None):
-               try:
-                       attr = getattr(self, attname)
-               except AttributeError:
-                       return default
-               if callable(attr):
-                       # Check func_code.co_argcount rather than try/excepting the
-                       # function and catching the TypeError, because something inside
-                       # the function may raise the TypeError. This technique is more
-                       # accurate.
-                       if hasattr(attr, 'func_code'):
-                               argcount = attr.func_code.co_argcount
-                       else:
-                               argcount = attr.__call__.func_code.co_argcount
-                       if argcount == 2: # one argument is 'self'
-                               return attr(obj)
-                       else:
-                               return attr()
-               return attr
-       
-       def feed_extra_kwargs(self, obj):
-               """Returns an extra keyword arguments dictionary that is used when initializing the feed generator."""
-               return {}
-       
-       def item_extra_kwargs(self, item):
-               """Returns an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator."""
-               return {}
-       
-       def item_title(self, item):
-               return escape(force_unicode(item))
-       
-       def item_description(self, item):
-               return force_unicode(item)
-       
-       class Meta:
-               abstract=True
-
 
 class Blog(Entity):
        """Represents a blog which can be posted to."""
@@ -395,7 +83,7 @@ register_value_model(BlogEntry)
 
 class BlogView(FeedView):
        """
-       A subclass of :class:`FeedView` which handles patterns and feeds for a :class:`Blog` and its related :class:`entries <BlogEntry>`.
+       A subclass of :class:`.FeedView` which handles patterns and feeds for a :class:`Blog` and its related :class:`entries <BlogEntry>`.
        
        """
        ENTRY_PERMALINK_STYLE_CHOICES = (
@@ -520,11 +208,11 @@ class BlogView(FeedView):
                return self.blog.entry_tags
        
        def get_all_entries(self, request, extra_context=None):
-               """Used to generate :meth:`~FeedView.feed_patterns` for all entries."""
+               """Used to generate :meth:`~.FeedView.feed_patterns` for all entries."""
                return self.get_entry_queryset(), extra_context
        
        def get_entries_by_ymd(self, request, year=None, month=None, day=None, extra_context=None):
-               """Used to generate :meth:`~FeedView.feed_patterns` for entries with a specific year, month, and day."""
+               """Used to generate :meth:`~.FeedView.feed_patterns` for entries with a specific year, month, and day."""
                if not self.entry_archive_page:
                        raise Http404
                entries = self.get_entry_queryset()
@@ -540,7 +228,7 @@ class BlogView(FeedView):
                return entries, context
        
        def get_entries_by_tag(self, request, tag_slugs, extra_context=None):
-               """Used to generate :meth:`~FeedView.feed_patterns` for entries with all of the given tags."""
+               """Used to generate :meth:`~.FeedView.feed_patterns` for entries with all of the given tags."""
                tag_slugs = tag_slugs.replace('+', '/').split('/')
                tags = self.get_tag_queryset().filter(slug__in=tag_slugs)
                
@@ -591,13 +279,13 @@ class BlogView(FeedView):
                })
                return self.tag_archive_page.render_to_response(request, extra_context=context)
        
-       def feed_view(self, get_items_attr, reverse_name):
-               """Overrides :meth:`FeedView.feed_view` to add :class:`.Tag`\ s to the feed as categories."""
+       def feed_view(self, get_items_attr, reverse_name, feed_type=None):
+               """Overrides :meth:`.FeedView.feed_view` to add :class:`.Tag`\ s to the feed as categories."""
                get_items = callable(get_items_attr) and get_items_attr or getattr(self, get_items_attr)
                
                def inner(request, extra_context=None, *args, **kwargs):
                        obj = self.get_object(request, *args, **kwargs)
-                       feed = self.get_feed(obj, request, reverse_name)
+                       feed = self.get_feed(obj, request, reverse_name, feed_type, *args, **kwargs)
                        items, extra_context = get_items(request, extra_context=extra_context, *args, **kwargs)
                        self.populate_feed(feed, items, request)
                        
@@ -616,7 +304,7 @@ class BlogView(FeedView):
                return inner
        
        def process_page_items(self, request, items):
-               """Overrides :meth:`FeedView.process_page_items` to add pagination."""
+               """Overrides :meth:`.FeedView.process_page_items` to add pagination."""
                if self.entries_per_page:
                        page_num = request.GET.get('page', 1)
                        paginator, paginated_page, items = paginate(items, self.entries_per_page, page_num)
@@ -725,7 +413,7 @@ register_value_model(NewsletterIssue)
 
 
 class NewsletterView(FeedView):
-       """A subclass of :class:`FeedView` which handles patterns and feeds for a :class:`Newsletter` and its related :class:`articles <NewsletterArticle>`."""
+       """A subclass of :class:`.FeedView` which handles patterns and feeds for a :class:`Newsletter` and its related :class:`articles <NewsletterArticle>`."""
        ARTICLE_PERMALINK_STYLE_CHOICES = (
                ('D', 'Year, month, and day'),
                ('M', 'Year and month'),
@@ -839,11 +527,11 @@ class NewsletterView(FeedView):
                return self.newsletter.issues.all()
        
        def get_all_articles(self, request, extra_context=None):
-               """Used to generate :meth:`FeedView.feed_patterns` for all entries."""
+               """Used to generate :meth:`~.FeedView.feed_patterns` for all entries."""
                return self.get_article_queryset(), extra_context
        
        def get_articles_by_ymd(self, request, year, month=None, day=None, extra_context=None):
-               """Used to generate :meth:`FeedView.feed_patterns` for a specific year, month, and day."""
+               """Used to generate :meth:`~.FeedView.feed_patterns` for a specific year, month, and day."""
                articles = self.get_article_queryset().filter(date__year=year)
                if month:
                        articles = articles.filter(date__month=month)
@@ -852,7 +540,7 @@ class NewsletterView(FeedView):
                return articles, extra_context
        
        def get_articles_by_issue(self, request, numbering, extra_context=None):
-               """Used to generate :meth:`FeedView.feed_patterns` for articles from a certain issue."""
+               """Used to generate :meth:`~.FeedView.feed_patterns` for articles from a certain issue."""
                try:
                        issue = self.get_issue_queryset().get(numbering=numbering)
                except NewsletterIssue.DoesNotExist:
index 85a0bc5..1031d73 100644 (file)
@@ -140,6 +140,22 @@ def recursenavigation(parser, token):
                        </li>
                    {% endrecursenavigation %}
                </ul>
+       
+       .. note:: {% recursenavigation %} requires that the current :class:`HttpRequest` be present in the context as ``request``. The simplest way to do this is with the `request context processor`_. If this is installed with just the default template context processors, the entry in your settings file will look like this::
+
+               TEMPLATE_CONTEXT_PROCESSORS = (
+                       # Defaults
+                       "django.contrib.auth.context_processors.auth",
+                       "django.core.context_processors.debug",
+                       "django.core.context_processors.i18n",
+                       "django.core.context_processors.media",
+                       "django.core.context_processors.static",
+                       "django.contrib.messages.context_processors.messages"
+                       ...
+                       "django.core.context_processors.request"
+               )
+       
+       .. _request context processor: https://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request
        """
        bits = token.contents.split()
        if len(bits) != 3:
index b35133e..ffe5871 100644 (file)
@@ -153,18 +153,6 @@ class Click(models.Model):
                get_latest_by = 'datetime'
 
 
-class RegistryChoiceField(SlugMultipleChoiceField):
-       def _get_choices(self):
-               if isinstance(self._choices, RegistryIterator):
-                       return self._choices.copy()
-               elif hasattr(self._choices, 'next'):
-                       choices, self._choices = itertools.tee(self._choices)
-                       return choices
-               else:
-                       return self._choices
-       choices = property(_get_choices)
-
-
 try:
        from south.modelsinspector import add_introspection_rules
 except ImportError:
@@ -177,8 +165,8 @@ class SearchView(MultiView):
        """Handles a view for the results of a search, anonymously tracks the selections made by end users, and provides an AJAX API for asynchronous search result loading. This can be particularly useful if some searches are slow."""
        #: :class:`ForeignKey` to a :class:`.Page` which will be used to render the search results.
        results_page = models.ForeignKey(Page, related_name='search_results_related')
-       #: A :class:`.SlugMultipleChoiceField` whose choices are the contents of the :class:`.SearchRegistry`
-       searches = RegistryChoiceField(choices=registry.iterchoices())
+       #: A :class:`.SlugMultipleChoiceField` whose choices are the contents of :obj:`.sobol.search.registry`
+       searches = SlugMultipleChoiceField(choices=registry.iterchoices())
        #: A :class:`BooleanField` which controls whether or not the AJAX API is enabled.
        #:
        #: .. note:: If the AJAX API is enabled, a ``ajax_api_url`` attribute will be added to each search instance containing the url and get parameters for an AJAX request to retrieve results for that search.
index eb2a333..a79030a 100644 (file)
@@ -12,7 +12,8 @@ from django.utils.safestring import mark_safe
 from django.utils.text import capfirst
 from django.template import loader, Context, Template, TemplateDoesNotExist
 
-from philo.contrib.sobol.utils import make_tracking_querydict, RegistryIterator
+from philo.contrib.sobol.utils import make_tracking_querydict
+from philo.utils.registry import Registry
 
 
 if getattr(settings, 'SOBOL_USE_EVENTLET', False):
@@ -25,7 +26,7 @@ else:
 
 
 __all__ = (
-       'Result', 'BaseSearch', 'DatabaseSearch', 'URLSearch', 'JSONSearch', 'GoogleSearch', 'SearchRegistry', 'registry', 'get_search_instance'
+       'Result', 'BaseSearch', 'DatabaseSearch', 'URLSearch', 'JSONSearch', 'GoogleSearch', 'registry', 'get_search_instance'
 )
 
 
@@ -33,74 +34,8 @@ SEARCH_CACHE_SEED = 'philo_sobol_search_results'
 USE_CACHE = getattr(settings, 'SOBOL_USE_CACHE', True)
 
 
-class RegistrationError(Exception):
-       """Raised if there is a problem registering a search with a :class:`SearchRegistry`"""
-       pass
-
-
-class SearchRegistry(object):
-       """Holds a registry of search types by slug."""
-       
-       def __init__(self):
-               self._registry = {}
-       
-       def register(self, search, slug=None):
-               """
-               Register a search with the registry.
-               
-               :param search: The search class to register - generally a subclass of :class:`BaseSearch`
-               :param slug: The slug which will be used to register the search class. If ``slug`` is ``None``, the search's default slug will be used.
-               :raises: :class:`RegistrationError` if a different search is already registered with ``slug``.
-               
-               """
-               slug = slug or search.slug
-               if slug in self._registry:
-                       registered = self._registry[slug]
-                       if registered.__module__ != search.__module__:
-                               raise RegistrationError("A different search is already registered as `%s`" % slug)
-               else:
-                       self._registry[slug] = search
-       
-       def unregister(self, search, slug=None):
-               """
-               Unregister a search from the registry.
-               
-               :param search: The search class to unregister - generally a subclass of :class:`BaseSearch`
-               :param slug: If provided, the search will only be removed if it was registered with ``slug``. If not provided, the search class will be unregistered no matter what slug it was registered with.
-               :raises: :class:`RegistrationError` if a slug is provided but the search registered with that slug is not ``search``.
-               
-               """
-               if slug is not None:
-                       if slug in self._registry and self._registry[slug] == search:
-                               del self._registry[slug]
-                       raise RegistrationError("`%s` is not registered as `%s`" % (search, slug))
-               else:
-                       for slug, search in self._registry.items():
-                               if search == search:
-                                       del self._registry[slug]
-       
-       def items(self):
-               """Returns a list of (slug, search) items in the registry."""
-               return self._registry.items()
-       
-       def iteritems(self):
-               """Returns an iterator over the (slug, search) pairs in the registry."""
-               return RegistryIterator(self._registry, 'iteritems')
-       
-       def iterchoices(self):
-               """Returns an iterator over (slug, search.verbose_name) pairs for the registry."""
-               return RegistryIterator(self._registry, 'iteritems', lambda x: (x[0], x[1].verbose_name))
-       
-       def __getitem__(self, key):
-               """Returns the search registered with ``key``."""
-               return self._registry[key]
-       
-       def __iter__(self):
-               """Returns an iterator over the keys in the registry."""
-               return self._registry.__iter__()
-
-
-registry = SearchRegistry()
+#: A registry for :class:`BaseSearch` subclasses that should be available in the admin.
+registry = Registry()
 
 
 def _make_cache_key(search, search_arg):
@@ -119,7 +54,6 @@ def get_search_instance(slug, search_arg):
        instance = search(search_arg)
        instance.slug = slug
        return instance
-       
 
 
 class Result(object):
diff --git a/philo/contrib/winer/__init__.py b/philo/contrib/winer/__init__.py
new file mode 100644 (file)
index 0000000..83fb303
--- /dev/null
@@ -0,0 +1,4 @@
+"""
+Winer provides the same API as `django's syndication Feed class <http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#django.contrib.syndication.django.contrib.syndication.views.Feed>`_, adapted to a Philo-style :class:`~philo.models.nodes.MultiView` for easy database management. Apps that need syndication can simply subclass :class:`~philo.contrib.winer.models.FeedView`, override a few methods, and start serving RSS and Atom feeds. See :class:`~philo.contrib.penfield.models.BlogView` for a concrete implementation example.
+
+"""
\ No newline at end of file
diff --git a/philo/contrib/winer/exceptions.py b/philo/contrib/winer/exceptions.py
new file mode 100644 (file)
index 0000000..e2045f9
--- /dev/null
@@ -0,0 +1,3 @@
+class HttpNotAcceptable(Exception):
+       """This will be raised in :meth:`.FeedView.get_feed_type` if an Http-Accept header will not accept any of the feed content types that are available."""
+       pass
\ No newline at end of file
diff --git a/philo/contrib/winer/feeds.py b/philo/contrib/winer/feeds.py
new file mode 100644 (file)
index 0000000..0554591
--- /dev/null
@@ -0,0 +1,13 @@
+from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
+
+from philo.utils.registry import Registry
+
+
+DEFAULT_FEED = Atom1Feed
+
+
+registry = Registry()
+
+
+registry.register(Atom1Feed, verbose_name='Atom')
+registry.register(Rss201rev2Feed, verbose_name='RSS')
\ No newline at end of file
similarity index 58%
rename from philo/contrib/penfield/middleware.py
rename to philo/contrib/winer/middleware.py
index a0cd649..89a5bd2 100644 (file)
@@ -1,11 +1,11 @@
 from django.http import HttpResponse
 from django.utils.decorators import decorator_from_middleware
 
-from philo.contrib.penfield.exceptions import HttpNotAcceptable
+from philo.contrib.winer.exceptions import HttpNotAcceptable
 
 
 class HttpNotAcceptableMiddleware(object):
-       """Middleware to catch :exc:`~philo.contrib.penfield.exceptions.HttpNotAcceptable` and return an :class:`HttpResponse` with a 406 response code. See :rfc:`2616`."""
+       """Middleware to catch :exc:`~philo.contrib.winer.exceptions.HttpNotAcceptable` and return an :class:`HttpResponse` with a 406 response code. See :rfc:`2616`."""
        def process_exception(self, request, exception):
                if isinstance(exception, HttpNotAcceptable):
                        return HttpResponse(status=406)
diff --git a/philo/contrib/winer/models.py b/philo/contrib/winer/models.py
new file mode 100644 (file)
index 0000000..5e85cc3
--- /dev/null
@@ -0,0 +1,350 @@
+from django.conf import settings
+from django.conf.urls.defaults import url, patterns, include
+from django.contrib.sites.models import Site, RequestSite
+from django.contrib.syndication.views import add_domain
+from django.db import models
+from django.http import HttpResponse
+from django.template import RequestContext, Template as DjangoTemplate
+from django.utils import feedgenerator, tzinfo
+from django.utils.encoding import smart_unicode, force_unicode
+from django.utils.html import escape
+
+from philo.contrib.winer.exceptions import HttpNotAcceptable
+from philo.contrib.winer.feeds import registry, DEFAULT_FEED
+from philo.contrib.winer.middleware import http_not_acceptable
+from philo.models import Page, Template, MultiView
+
+try:
+       import mimeparse
+except:
+       mimeparse = None
+
+
+class FeedView(MultiView):
+       """
+       :class:`FeedView` is an abstract model which handles a number of pages and related feeds for a single object such as a blog or newsletter. In addition to all other methods and attributes, :class:`FeedView` supports the same generic API as `django.contrib.syndication.views.Feed <http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#django.contrib.syndication.django.contrib.syndication.views.Feed>`_.
+       
+       """
+       #: The type of feed which should be served by the :class:`FeedView`.
+       feed_type = models.CharField(max_length=50, choices=registry.choices, default=registry.get_slug(DEFAULT_FEED))
+       #: The suffix which will be appended to a page URL for a :attr:`feed_type` feed of its items. Default: "feed". Note that RSS and Atom feeds will always be available at ``<page_url>/rss`` and ``<page_url>/atom`` regardless of the value of this setting.
+       #:
+       #: .. seealso:: :meth:`get_feed_type`, :meth:`feed_patterns`
+       feed_suffix = models.CharField(max_length=255, blank=False, default="feed")
+       #: A :class:`BooleanField` - whether or not feeds are enabled.
+       feeds_enabled = models.BooleanField(default=True)
+       #: A :class:`PositiveIntegerField` - the maximum number of items to return for this feed. All items will be returned if this field is blank. Default: 15.
+       feed_length = models.PositiveIntegerField(blank=True, null=True, default=15, help_text="The maximum number of items to return for this feed. All items will be returned if this field is blank.")
+       
+       #: A :class:`ForeignKey` to a :class:`.Template` which will be used to render the title of each item in the feed if provided.
+       item_title_template = models.ForeignKey(Template, blank=True, null=True, related_name="%(app_label)s_%(class)s_title_related")
+       #: A :class:`ForeignKey` to a :class:`.Template` which will be used to render the description of each item in the feed if provided.
+       item_description_template = models.ForeignKey(Template, blank=True, null=True, related_name="%(app_label)s_%(class)s_description_related")
+       
+       #: An attribute holding the name of the context variable to be populated with the items managed by the :class:`FeedView`. Default: "items"
+       item_context_var = 'items'
+       #: An attribute holding the name of the attribute on a subclass of :class:`FeedView` which will contain the main object of a feed (such as a :class:`~philo.contrib.penfield.models.Blog`.) Default: "object"
+       #:
+       #: Example::
+       #:
+       #:     class BlogView(FeedView):
+       #:         blog = models.ForeignKey(Blog)
+       #:         
+       #:         object_attr = 'blog'
+       #:         item_context_var = 'entries'
+       object_attr = 'object'
+       
+       #: An attribute holding a description of the feeds served by the :class:`FeedView`. This is a required part of the :class:`django.contrib.syndication.view.Feed` API.
+       description = ""
+       
+       def feed_patterns(self, base, get_items_attr, page_attr, reverse_name):
+               """
+               Given the name to be used to reverse this view and the names of the attributes for the function that fetches the objects, returns patterns suitable for inclusion in urlpatterns. In addition to ``base`` (which will serve the page at ``page_attr``) and ``base`` + :attr:`feed_suffix` (which will serve a :attr:`feed_type` feed), patterns will be provided for each registered feed type as ``base`` + ``slug``.
+               
+               :param base: The base of the returned patterns - that is, the subpath pattern which will reference the page for the items. The :attr:`feed_suffix` will be appended to this subpath.
+               :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` which will return an (``items``, ``extra_context``) tuple. This will be passed directly to :meth:`feed_view` and :meth:`page_view`.
+               :param page_attr: A :class:`.Page` instance or the name of an attribute on the :class:`FeedView` which contains a :class:`.Page` instance. This will be passed directly to :meth:`page_view` and will be rendered with the items from ``get_items_attr``.
+               :param reverse_name: The string which is considered the "name" of the view function returned by :meth:`page_view` for the given parameters.
+               :returns: Patterns suitable for use in urlpatterns.
+               
+               Example::
+               
+                       class BlogView(FeedView):
+                           blog = models.ForeignKey(Blog)
+                           entry_archive_page = models.ForeignKey(Page)
+                           
+                           @property
+                           def urlpatterns(self):
+                               urlpatterns = self.feed_patterns(r'^', 'get_all_entries', 'index_page', 'index')
+                               urlpatterns += self.feed_patterns(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})', 'get_entries_by_ymd', 'entry_archive_page', 'entries_by_day')
+                               return urlpatterns
+                           
+                           def get_entries_by_ymd(request, year, month, day, extra_context=None):
+                               entries = Blog.entries.all()
+                               # filter entries based on the year, month, and day.
+                               return entries, extra_context
+               
+               .. seealso:: :meth:`get_feed_type`
+               
+               """
+               urlpatterns = patterns('')
+               if self.feeds_enabled:
+                       suffixes = [(self.feed_suffix, None)] + [(slug, slug) for slug in registry]
+                       for suffix, feed_type in suffixes:
+                               feed_view = http_not_acceptable(self.feed_view(get_items_attr, reverse_name, feed_type))
+                               feed_pattern = r'%s%s%s$' % (base, "/" if base and base[-1] != "^" else "", suffix)
+                               urlpatterns += patterns('',
+                                       url(feed_pattern, feed_view, name="%s_%s" % (reverse_name, suffix)),
+                               )
+               urlpatterns += patterns('',
+                       url(r"%s$" % base, self.page_view(get_items_attr, page_attr), name=reverse_name)
+               )
+               return urlpatterns
+       
+       def get_object(self, request, **kwargs):
+               """By default, returns the object stored in the attribute named by :attr:`object_attr`. This can be overridden for subclasses that publish different data for different URL parameters. It is part of the :class:`django.contrib.syndication.views.Feed` API."""
+               return getattr(self, self.object_attr)
+       
+       def feed_view(self, get_items_attr, reverse_name, feed_type=None):
+               """
+               Returns a view function that renders a list of items as a feed.
+               
+               :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` that will return a (items, extra_context) tuple when called with view arguments.
+               :param reverse_name: The name which can be used reverse the page for this feed using the :class:`FeedView` as the urlconf.
+               :param feed_type: The slug used to render the feed class which will be used by the returned view function.
+               
+               :returns: A view function that renders a list of items as a feed.
+               
+               """
+               get_items = get_items_attr if callable(get_items_attr) else getattr(self, get_items_attr)
+               
+               def inner(request, extra_context=None, *args, **kwargs):
+                       obj = self.get_object(request, *args, **kwargs)
+                       feed = self.get_feed(obj, request, reverse_name, feed_type, *args, **kwargs)
+                       items, xxx = get_items(request, extra_context=extra_context, *args, **kwargs)
+                       self.populate_feed(feed, items, request)
+                       
+                       response = HttpResponse(mimetype=feed.mime_type)
+                       feed.write(response, 'utf-8')
+                       return response
+               
+               return inner
+       
+       def page_view(self, get_items_attr, page_attr):
+               """
+               :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` that will return a (items, extra_context) tuple when called with view arguments.
+               :param page_attr: A :class:`.Page` instance or the name of an attribute on the :class:`FeedView` which contains a :class:`.Page` instance. This will be rendered with the items from ``get_items_attr``.
+               
+               :returns: A view function that renders a list of items as an :class:`HttpResponse`.
+               
+               """
+               get_items = get_items_attr if callable(get_items_attr) else getattr(self, get_items_attr)
+               page = page_attr if isinstance(page_attr, Page) else getattr(self, page_attr)
+               
+               def inner(request, extra_context=None, *args, **kwargs):
+                       items, extra_context = get_items(request, extra_context=extra_context, *args, **kwargs)
+                       items, item_context = self.process_page_items(request, items)
+                       
+                       context = self.get_context()
+                       context.update(extra_context or {})
+                       context.update(item_context or {})
+                       
+                       return page.render_to_response(request, extra_context=context)
+               return inner
+       
+       def process_page_items(self, request, items):
+               """
+               Hook for handling any extra processing of ``items`` based on an :class:`HttpRequest`, such as pagination or searching. This method is expected to return a list of items and a dictionary to be added to the page context.
+               
+               """
+               item_context = {
+                       self.item_context_var: items
+               }
+               return items, item_context
+       
+       def get_feed_type(self, request, feed_type=None):
+               """
+               If ``feed_type`` is not ``None``, returns the corresponding class from the registry or raises :exc:`.HttpNotAcceptable`.
+               
+               Otherwise, intelligently chooses a feed type for a given request. Tries to return :attr:`feed_type`, but if the Accept header does not include that mimetype, tries to return the best match from the feed types that are offered by the :class:`FeedView`. If none of the offered feed types are accepted by the :class:`HttpRequest`, raises :exc:`.HttpNotAcceptable`.
+               
+               If `mimeparse <http://code.google.com/p/mimeparse/>`_ is installed, it will be used to select the best matching accepted format; otherwise, the first available format that is accepted will be selected.
+               
+               """
+               if feed_type is not None:
+                       feed_type = registry[feed_type]
+                       loose = False
+               else:
+                       feed_type = registry.get(self.feed_type, DEFAULT_FEED)
+                       loose = True
+               mt = feed_type.mime_type
+               accept = request.META.get('HTTP_ACCEPT')
+               if accept and mt not in accept and "*/*" not in accept and "%s/*" % mt.split("/")[0] not in accept:
+                       # Wups! They aren't accepting the chosen format.
+                       feed_type = None
+                       if loose:
+                               # Is there another format we can use?
+                               accepted_mts = dict([(obj.mime_type, obj) for obj in registry.values()])
+                               if mimeparse:
+                                       mt = mimeparse.best_match(accepted_mts.keys(), accept)
+                                       if mt:
+                                               feed_type = accepted_mts[mt]
+                               else:
+                                       for mt in accepted_mts:
+                                               if mt in accept or "%s/*" % mt.split("/")[0] in accept:
+                                                       feed_type = accepted_mts[mt]
+                                                       break
+                       if not feed_type:
+                               raise HttpNotAcceptable
+               return feed_type
+       
+       def get_feed(self, obj, request, reverse_name, feed_type=None, *args, **kwargs):
+               """
+               Returns an unpopulated :class:`django.utils.feedgenerator.DefaultFeed` object for this object.
+               
+               :param obj: The object for which the feed should be generated.
+               :param request: The current request.
+               :param reverse_name: The name which can be used to reverse the URL of the page corresponding to this feed.
+               :param feed_type: The slug used to register the feed class that will be instantiated and returned.
+               
+               :returns: An instance of the feed class registered as ``feed_type``, falling back to :attr:`feed_type` if ``feed_type`` is ``None``.
+               
+               """
+               try:
+                       current_site = Site.objects.get_current()
+               except Site.DoesNotExist:
+                       current_site = RequestSite(request)
+               
+               feed_type = self.get_feed_type(request, feed_type)
+               node = request.node
+               link = node.construct_url(self.reverse(reverse_name, args=args, kwargs=kwargs), with_domain=True, request=request, secure=request.is_secure())
+               
+               feed = feed_type(
+                       title = self.__get_dynamic_attr('title', obj),
+                       subtitle = self.__get_dynamic_attr('subtitle', obj),
+                       link = link,
+                       description = self.__get_dynamic_attr('description', obj),
+                       language = settings.LANGUAGE_CODE.decode(),
+                       feed_url = add_domain(
+                               current_site.domain,
+                               self.__get_dynamic_attr('feed_url', obj) or node.construct_url(self.reverse("%s_%s" % (reverse_name, registry.get_slug(feed_type)), args=args, kwargs=kwargs), with_domain=True, request=request, secure=request.is_secure()),
+                               request.is_secure()
+                       ),
+                       author_name = self.__get_dynamic_attr('author_name', obj),
+                       author_link = self.__get_dynamic_attr('author_link', obj),
+                       author_email = self.__get_dynamic_attr('author_email', obj),
+                       categories = self.__get_dynamic_attr('categories', obj),
+                       feed_copyright = self.__get_dynamic_attr('feed_copyright', obj),
+                       feed_guid = self.__get_dynamic_attr('feed_guid', obj),
+                       ttl = self.__get_dynamic_attr('ttl', obj),
+                       **self.feed_extra_kwargs(obj)
+               )
+               return feed
+       
+       def populate_feed(self, feed, items, request):
+               """Populates a :class:`django.utils.feedgenerator.DefaultFeed` instance as is returned by :meth:`get_feed` with the passed-in ``items``."""
+               if self.item_title_template:
+                       title_template = DjangoTemplate(self.item_title_template.code)
+               else:
+                       title_template = None
+               if self.item_description_template:
+                       description_template = DjangoTemplate(self.item_description_template.code)
+               else:
+                       description_template = None
+               
+               node = request.node
+               try:
+                       current_site = Site.objects.get_current()
+               except Site.DoesNotExist:
+                       current_site = RequestSite(request)
+               
+               if self.feed_length is not None:
+                       items = items[:self.feed_length]
+               
+               for item in items:
+                       if title_template is not None:
+                               title = title_template.render(RequestContext(request, {'obj': item}))
+                       else:
+                               title = self.__get_dynamic_attr('item_title', item)
+                       if description_template is not None:
+                               description = description_template.render(RequestContext(request, {'obj': item}))
+                       else:
+                               description = self.__get_dynamic_attr('item_description', item)
+                       
+                       link = node.construct_url(self.reverse(obj=item), with_domain=True, request=request, secure=request.is_secure())
+                       
+                       enc = None
+                       enc_url = self.__get_dynamic_attr('item_enclosure_url', item)
+                       if enc_url:
+                               enc = feedgenerator.Enclosure(
+                                       url = smart_unicode(add_domain(
+                                                       current_site.domain,
+                                                       enc_url,
+                                                       request.is_secure()
+                                       )),
+                                       length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)),
+                                       mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item))
+                               )
+                       author_name = self.__get_dynamic_attr('item_author_name', item)
+                       if author_name is not None:
+                               author_email = self.__get_dynamic_attr('item_author_email', item)
+                               author_link = self.__get_dynamic_attr('item_author_link', item)
+                       else:
+                               author_email = author_link = None
+                       
+                       pubdate = self.__get_dynamic_attr('item_pubdate', item)
+                       if pubdate and not pubdate.tzinfo:
+                               ltz = tzinfo.LocalTimezone(pubdate)
+                               pubdate = pubdate.replace(tzinfo=ltz)
+                       
+                       feed.add_item(
+                               title = title,
+                               link = link,
+                               description = description,
+                               unique_id = self.__get_dynamic_attr('item_guid', item, link),
+                               enclosure = enc,
+                               pubdate = pubdate,
+                               author_name = author_name,
+                               author_email = author_email,
+                               author_link = author_link,
+                               categories = self.__get_dynamic_attr('item_categories', item),
+                               item_copyright = self.__get_dynamic_attr('item_copyright', item),
+                               **self.item_extra_kwargs(item)
+                       )
+       
+       def __get_dynamic_attr(self, attname, obj, default=None):
+               try:
+                       attr = getattr(self, attname)
+               except AttributeError:
+                       return default
+               if callable(attr):
+                       # Check func_code.co_argcount rather than try/excepting the
+                       # function and catching the TypeError, because something inside
+                       # the function may raise the TypeError. This technique is more
+                       # accurate.
+                       if hasattr(attr, 'func_code'):
+                               argcount = attr.func_code.co_argcount
+                       else:
+                               argcount = attr.__call__.func_code.co_argcount
+                       if argcount == 2: # one argument is 'self'
+                               return attr(obj)
+                       else:
+                               return attr()
+               return attr
+       
+       def feed_extra_kwargs(self, obj):
+               """Returns an extra keyword arguments dictionary that is used when initializing the feed generator."""
+               return {}
+       
+       def item_extra_kwargs(self, item):
+               """Returns an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator."""
+               return {}
+       
+       def item_title(self, item):
+               return escape(force_unicode(item))
+       
+       def item_description(self, item):
+               return force_unicode(item)
+       
+       class Meta:
+               abstract=True
\ No newline at end of file
diff --git a/philo/migrations/0018_auto__chg_field_node_view_object_id__chg_field_node_view_content_type.py b/philo/migrations/0018_auto__chg_field_node_view_object_id__chg_field_node_view_content_type.py
new file mode 100644 (file)
index 0000000..b2e6a5e
--- /dev/null
@@ -0,0 +1,144 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Changing field 'Node.view_object_id'
+        db.alter_column('philo_node', 'view_object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True))
+
+        # Changing field 'Node.view_content_type'
+        db.alter_column('philo_node', 'view_content_type_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, to=orm['contenttypes.ContentType']))
+
+
+    def backwards(self, orm):
+        
+        # User chose to not deal with backwards NULL issues for 'Node.view_object_id'
+        raise RuntimeError("Cannot reverse this migration. 'Node.view_object_id' and its values cannot be restored.")
+
+        # User chose to not deal with backwards NULL issues for 'Node.view_content_type'
+        raise RuntimeError("Cannot reverse this migration. 'Node.view_content_type' and its values cannot be restored.")
+
+
+    models = {
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'philo.attribute': {
+            'Meta': {'unique_together': "(('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))", 'object_name': 'Attribute'},
+            'entity_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'attribute_entity_set'", 'to': "orm['contenttypes.ContentType']"}),
+            'entity_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
+            'value_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'attribute_value_set'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
+            'value_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'})
+        },
+        'philo.collection': {
+            'Meta': {'object_name': 'Collection'},
+            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'philo.collectionmember': {
+            'Meta': {'object_name': 'CollectionMember'},
+            'collection': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'members'", 'to': "orm['philo.Collection']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'index': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
+            'member_content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'member_object_id': ('django.db.models.fields.PositiveIntegerField', [], {})
+        },
+        'philo.contentlet': {
+            'Meta': {'object_name': 'Contentlet'},
+            'content': ('philo.models.fields.TemplateField', [], {}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
+            'page': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'contentlets'", 'to': "orm['philo.Page']"})
+        },
+        'philo.contentreference': {
+            'Meta': {'object_name': 'ContentReference'},
+            'content_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
+            'page': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'contentreferences'", 'to': "orm['philo.Page']"})
+        },
+        'philo.file': {
+            'Meta': {'object_name': 'File'},
+            'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'mimetype': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'philo.foreignkeyvalue': {
+            'Meta': {'object_name': 'ForeignKeyValue'},
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'})
+        },
+        'philo.jsonvalue': {
+            'Meta': {'object_name': 'JSONValue'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'value': ('philo.models.fields.JSONField', [], {'default': "'null'", 'db_index': 'True'})
+        },
+        'philo.manytomanyvalue': {
+            'Meta': {'object_name': 'ManyToManyValue'},
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'values': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['philo.ForeignKeyValue']", 'null': 'True', 'blank': 'True'})
+        },
+        'philo.node': {
+            'Meta': {'object_name': 'Node'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
+            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'view_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'node_view_set'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
+            'view_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'})
+        },
+        'philo.page': {
+            'Meta': {'object_name': 'Page'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'template': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'pages'", 'to': "orm['philo.Template']"}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'philo.redirect': {
+            'Meta': {'object_name': 'Redirect'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'reversing_parameters': ('philo.models.fields.JSONField', [], {'blank': 'True'}),
+            'status_code': ('django.db.models.fields.IntegerField', [], {'default': '302'}),
+            'target_node': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'philo_redirect_related'", 'null': 'True', 'to': "orm['philo.Node']"}),
+            'url_or_subpath': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'})
+        },
+        'philo.tag': {
+            'Meta': {'ordering': "('name',)", 'object_name': 'Tag'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'})
+        },
+        'philo.template': {
+            'Meta': {'object_name': 'Template'},
+            'code': ('philo.models.fields.TemplateField', [], {}),
+            'documentation': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'mimetype': ('django.db.models.fields.CharField', [], {'default': "'text/html'", 'max_length': '255'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['philo.Template']"}),
+            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
+            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
+        }
+    }
+
+    complete_apps = ['philo']
index efd315f..7ab4326 100644 (file)
@@ -7,6 +7,7 @@ from django.utils.text import capfirst
 from django.utils.translation import ugettext_lazy as _
 
 from philo.forms.fields import JSONFormField
+from philo.utils.registry import RegistryIterator
 from philo.validators import TemplateValidator, json_validator
 #from philo.models.fields.entities import *
 
@@ -71,7 +72,7 @@ class JSONField(models.TextField):
 
 
 class SlugMultipleChoiceField(models.Field):
-       """Stores a selection of multiple items with unique slugs in the form of a comma-separated list."""
+       """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices."""
        __metaclass__ = models.SubfieldBase
        description = _("Comma-separated slug field")
        
@@ -127,6 +128,16 @@ class SlugMultipleChoiceField(models.Field):
                if invalid_values:
                        # should really make a custom message.
                        raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
+       
+       def _get_choices(self):
+               if isinstance(self._choices, RegistryIterator):
+                       return self._choices.copy()
+               elif hasattr(self._choices, 'next'):
+                       choices, self._choices = itertools.tee(self._choices)
+                       return choices
+               else:
+                       return self._choices
+       choices = property(_get_choices)
 
 
 try:
index 93f772a..5b8b8ed 100644 (file)
@@ -31,8 +31,8 @@ class Node(SlugTreeEntity):
        :class:`Node`\ s are the basic building blocks of a website using Philo. They define the URL hierarchy and connect each URL to a :class:`View` subclass instance which is used to generate an HttpResponse.
        
        """
-       view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
-       view_object_id = models.PositiveIntegerField()
+       view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter, blank=True, null=True)
+       view_object_id = models.PositiveIntegerField(blank=True, null=True)
        #: :class:`GenericForeignKey` to a non-abstract subclass of :class:`View`
        view = generic.GenericForeignKey('view_content_type', 'view_object_id')
        
@@ -44,11 +44,15 @@ class Node(SlugTreeEntity):
                return False
        
        def handles_subpath(self, subpath):
-               return self.view.handles_subpath(subpath)
+               if self.view:
+                       return self.view.handles_subpath(subpath)
+               return False
        
        def render_to_response(self, request, extra_context=None):
                """This is a shortcut method for :meth:`View.render_to_response`"""
-               return self.view.render_to_response(request, extra_context)
+               if self.view:
+                       return self.view.render_to_response(request, extra_context)
+               raise Http404
        
        def get_absolute_url(self, request=None, with_domain=False, secure=False):
                """
diff --git a/philo/utils/registry.py b/philo/utils/registry.py
new file mode 100644 (file)
index 0000000..1673429
--- /dev/null
@@ -0,0 +1,141 @@
+from django.core.validators import slug_re
+from django.template.defaultfilters import slugify
+from django.utils.encoding import smart_str
+
+
+class RegistryIterator(object):
+       """
+       Wraps the iterator returned by calling ``getattr(registry, iterattr)`` to provide late instantiation of the wrapped iterator and to allow copying of the iterator for even later instantiation.
+       
+       :param registry: The object which provides the iterator at ``iterattr``.
+       :param iterattr: The name of the method on ``registry`` that provides the iterator.
+       :param transform: A function which will be called on each result from the wrapped iterator before it is returned.
+       
+       """
+       def __init__(self, registry, iterattr='__iter__', transform=lambda x:x):
+               if not hasattr(registry, iterattr):
+                       raise AttributeError("Registry has no attribute %s" % iterattr)
+               self.registry = registry
+               self.iterattr = iterattr
+               self.transform = transform
+       
+       def __iter__(self):
+               return self
+       
+       def next(self):
+               if not hasattr(self, '_iter'):
+                       self._iter = getattr(self.registry, self.iterattr)()
+               
+               return self.transform(self._iter.next())
+       
+       def copy(self):
+               """Returns a fresh copy of this iterator."""
+               return self.__class__(self.registry, self.iterattr, self.transform)
+
+
+class RegistrationError(Exception):
+       """Raised if there is a problem registering a object with a :class:`Registry`"""
+       pass
+
+
+class Registry(object):
+       """Holds a registry of arbitrary objects by slug."""
+       
+       def __init__(self):
+               self._registry = {}
+       
+       def register(self, obj, slug=None, verbose_name=None):
+               """
+               Register an object with the registry.
+               
+               :param obj: The object to register.
+               :param slug: The slug which will be used to register the object. If ``slug`` is ``None``, it will be generated from ``verbose_name`` or looked for at ``obj.slug``.
+               :param verbose_name: The verbose name for the object. If ``verbose_name`` is ``None``, it will be looked for at ``obj.verbose_name``.
+               :raises: :class:`RegistrationError` if a different object is already registered with ``slug``, or if ``slug`` is not a valid slug.
+               
+               """
+               verbose_name = verbose_name if verbose_name is not None else obj.verbose_name
+               
+               if slug is None:
+                       slug = getattr(obj, 'slug', slugify(verbose_name))
+               slug = smart_str(slug)
+               
+               if not slug_re.search(slug):
+                       raise RegistrationError(u"%s is not a valid slug." % slug)
+               
+               
+               if slug in self._registry:
+                       reg = self._registry[slug]
+                       if reg['obj'] != obj:
+                               raise RegistrationError(u"A different object is already registered as `%s`" % slug)
+               else:
+                       self._registry[slug] = {
+                               'obj': obj,
+                               'verbose_name': verbose_name
+                       }
+       
+       def unregister(self, obj, slug=None):
+               """
+               Unregister an object from the registry.
+               
+               :param obj: The object to unregister.
+               :param slug: If provided, the object will only be removed if it was registered with ``slug``. If not provided, the object will be unregistered no matter what slug it was registered with.
+               :raises: :class:`RegistrationError` if ``slug`` is provided and an object other than ``obj`` is registered as ``slug``.
+               
+               """
+               if slug is not None:
+                       if slug in self._registry:
+                               if self._registry[slug]['obj'] == obj:
+                                       del self._registry[slug]
+                               else:
+                                       raise RegistrationError(u"`%s` is not registered as `%s`" % (obj, slug))
+               else:
+                       for slug, reg in self.items():
+                               if obj == reg:
+                                       del self._registry[slug]
+       
+       def items(self):
+               """Returns a list of (slug, obj) items in the registry."""
+               return [(slug, self[slug]) for slug in self._registry]
+       
+       def values(self):
+               """Returns a list of objects in the registry."""
+               return [self[slug] for slug in self._registry]
+       
+       def iteritems(self):
+               """Returns a :class:`RegistryIterator` over the (slug, obj) pairs in the registry."""
+               return RegistryIterator(self._registry, 'iteritems', lambda x: (x[0], x[1]['obj']))
+       
+       def itervalues(self):
+               """Returns a :class:`RegistryIterator` over the objects in the registry."""
+               return RegistryIterator(self._registry, 'itervalues', lambda x: x['obj'])
+       
+       def iterchoices(self):
+               """Returns a :class:`RegistryIterator` over (slug, verbose_name) pairs for the registry."""
+               return RegistryIterator(self._registry, 'iteritems', lambda x: (x[0], x[1]['verbose_name']))
+       choices = property(iterchoices)
+       
+       def get(self, key, default=None):
+               """Returns the object registered with ``key`` or ``default`` if no object was registered."""
+               try:
+                       return self[key]
+               except KeyError:
+                       return default
+       
+       def get_slug(self, obj, default=None):
+               """Returns the slug used to register ``obj`` or ``default`` if ``obj`` was not registered."""
+               for slug, reg in self.iteritems():
+                       if obj == reg:
+                               return slug
+               return default
+       
+       def __getitem__(self, key):
+               """Returns the obj registered with ``key``."""
+               return self._registry[key]['obj']
+       
+       def __iter__(self):
+               """Returns an iterator over the keys in the registry."""
+               return self._registry.__iter__()
+       
+       def __contains__(self, item):
+               return self._registry.__contains__(item)
\ No newline at end of file