1. Dan Watson
  2. leaves-cms

Commits

Dan Watson  committed 6507600

Switch to use config instead of preferences

  • Participants
  • Parent commits 4c7a440
  • Branches default

Comments (0)

Files changed (18)

File leaves/admin.py

View file
  • Ignore whitespace
 	list_display = ('__unicode__', 'content_type', 'object_id', 'field', 'language')
 	list_filter = ('content_type', 'language')
 
-class PreferencesAdmin (UserSiteAdmin):
-	list_display = ('site', 'theme')
+class ConfigAdmin (UserSiteAdmin):
+	list_display = ('site',)
+	list_filter = ('site',)
 
 class RedirectAdmin (UserSiteAdmin):
 	list_display = ('old_path', 'new_path', 'site', 'redirect_type')
 admin.site.register(Comment, CommentAdmin)
 admin.site.register(Tag, TagAdmin)
 admin.site.register(Translation, TranslationAdmin)
-admin.site.register(Preferences, PreferencesAdmin)
+admin.site.register(Preferences, ConfigAdmin)
 admin.site.register(Redirect, RedirectAdmin)
 admin.site.register(UserSites)

File leaves/feeds.py

View file
  • Ignore whitespace
 from django.shortcuts import get_object_or_404
 from django.contrib.auth.models import User
 from leaves.models import Leaf
-from leaves.utils import get_site, format_text
+from leaves.utils import get_site, format_text, config
 
 class LeafItemFeed (Feed):
 
         return '%s: Recent Entries' % site.name
 
     def items(self):
-        site = get_site()
         resolved_items = []
-        for item in Leaf.on_site.active().filter(feed=True).order_by('-pub_date')[:site.preferences.feed_count]:
+        for item in Leaf.on_site.active().filter(feed=True).order_by('-pub_date')[:config.feed_count]:
             resolved_items.append(item.resolve())
         return resolved_items
 
         return '%s: Recent entries tagged with "%s"' % (site.name, obj.name)
 
     def items(self, obj):
-        site = get_site()
         resolved_items = []
-        for item in Leaf.on_site.active().filter(tags=obj, feed=True).order_by('-pub_date')[:site.preferences.feed_count]:
+        for item in Leaf.on_site.active().filter(tags=obj, feed=True).order_by('-pub_date')[:config.feed_count]:
             resolved_items.append(item.resolve())
         return resolved_items
 
         return '%s: Recent entries by %s' % (site.name, name)
 
     def items(self, obj):
-        site = get_site()
         resolved_items = []
-        for item in Leaf.on_site.active().filter(author_user=obj, feed=True).order_by('-pub_date')[:site.preferences.feed_count]:
+        for item in Leaf.on_site.active().filter(author_user=obj, feed=True).order_by('-pub_date')[:config.feed_count]:
             resolved_items.append(item.resolve())
         return resolved_items

File leaves/loaders.py

View file
  • Ignore whitespace
 from django.conf import settings
 from django.template.base import TemplateDoesNotExist
 from django.template.loader import BaseLoader
-from django.contrib.sites.models import Site
-from leaves.utils import get_site, get_theme_dir
+from leaves.utils import get_theme_dir, config
 import os
 
 class ThemeLoader (BaseLoader):
 
 	def load_template_source(self, template_name, template_dirs=None):
 		try:
-			site = get_site()
-			theme_path = get_theme_dir(site.preferences.theme)
+			theme_path = get_theme_dir(config.theme)
 			template_file = os.path.join(theme_path, 'templates', template_name)
 			f = open(template_file, 'rb')
 			try:

File leaves/managers.py

View file
  • Ignore whitespace
 from django.db import models
 from django.conf import settings
-from leaves.utils import filter_active_leaves, get_leaf_classes, get_site
+from leaves.utils import filter_active_leaves, get_leaf_classes, get_site, config
 
 class RequestSiteManager (models.Manager):
 	"""
 		return qs
 
 	def stream(self, select_related=True):
-		site = get_site()
-		return self.active(select_related).filter(subclass__in=site.preferences.stream_types.all(), stream=True)
+		return self.active(select_related).filter(subclass__in=config.stream_types.all(), stream=True)

File leaves/middleware.py

View file
  • Ignore whitespace
 		# to find the most specific.
 		all_sites = {}
 		default_site = None
-		for s in Site.objects.select_related('preferences'):
+		for s in Site.objects.select_related('leaves_config'):
 			all_sites[s.domain.lower()] = s
 			if s.pk == settings.SITE_ID:
 				default_site = s

File leaves/models.py

View file
  • Ignore whitespace
 			types_pks.append(ContentType.objects.get_for_model(klass).pk)
 	return types_pks
 
-class Preferences (models.Model):
-	DATE_ARCHIVE_CHOICES = (
-		('month', 'Monthly'),
-		('year', 'Yearly'),
-	)
+class SiteConfig (models.Model):
+	site = models.OneToOneField(Site, unique=True, related_name='%(app_label)s_config')
 
-	site = models.OneToOneField(Site, related_name='preferences', unique=True)
+	class Meta:
+		abstract = True
+
+	def save(self, **kwargs):
+		return super(SiteConfig, self).save(**kwargs)
+
+class Preferences (SiteConfig):
 	theme = models.CharField(max_length=100, choices=settings.AVAILABLE_THEMES, default='default')
 	stream_count = models.PositiveIntegerField(default=10)
 	stream_types = models.ManyToManyField(ContentType, blank=True, related_name='preferences', limit_choices_to={'pk__in': leaf_types})
 	default_comment_status = models.CharField(max_length=10, choices=COMMENT_STATUS_CHOICES, default=settings.LEAVES_DEFAULT_COMMENT_STATUS)
 	feed_count = models.PositiveIntegerField(default=5)
-	date_archives = models.CharField(max_length=5, choices=DATE_ARCHIVE_CHOICES, default='month')
-
+	analytics_id = models.CharField(max_length=50, blank=True)
+	
 	class Meta:
 		verbose_name_plural = _('preferences')
 
-	def __unicode__(self):
-		return u'%s preferences' % self.site
-
-class PluginConfig (models.Model):
-	site = models.OneToOneField(Site, unique=True)
-
-	class Meta:
-		abstract = True
-
-@receiver(post_save, sender=Site, dispatch_uid='leaves.models.create_site_preferences')
-def create_site_preferences(sender, **kwargs):
-	if kwargs['created']:
-		Preferences.objects.create(site=kwargs['instance'])
-
 class UserSites (models.Model):
 	user = models.OneToOneField(User, related_name='memberships', unique=True)
 	sites = models.ManyToManyField(Site, related_name='members', blank=True)

File leaves/plugins/archive/admin.py

View file
  • Ignore whitespace
+from django.contrib import admin
+from leaves.plugins.archive.models import Config
+from leaves.admin import ConfigAdmin
+
+admin.site.register(Config, ConfigAdmin)

File leaves/plugins/archive/models.py

View file
  • Ignore whitespace
+from django.db import models
+from leaves.models import SiteConfig
+
+DATE_ARCHIVE_CHOICES = (
+	('month', 'Monthly'),
+	('year', 'Yearly'),
+)
+
+class Config (SiteConfig):
+	enabled = models.BooleanField(default=True)
+	nav_link = models.BooleanField(default=False)
+	nav_dates = models.BooleanField(default=True)
+	archive_type = models.CharField(max_length=5, choices=DATE_ARCHIVE_CHOICES, default='month')

File leaves/plugins/archive/templatetags/archive.py

View file
  • Ignore whitespace
 from django import template
 from django.conf import settings
 from leaves.models import Leaf
+from leaves.utils import config
 
 register = template.Library()
 
 @register.inclusion_tag('archive/date_list.html')
-def archive_dates(group='month', current=None):
-    dates = [d.date() for d in Leaf.on_site.stream().dates('pub_date', group, order='DESC')]
-    return {
-        'dates': dates,
-        'group': group,
-        'current': current,
-    }
+def archive_dates(current=None):
+	group = config.archive.archive_type
+	dates = [d.date() for d in Leaf.on_site.stream().dates('pub_date', group, order='DESC')]
+	return {
+		'dates': dates,
+		'group': group,
+		'current': current,
+	}

File leaves/plugins/archive/views.py

View file
  • Ignore whitespace
 from django.conf import settings
 from django.http import Http404
 from leaves.models import Leaf
-from leaves.utils import get_page
+from leaves.utils import get_page, config
 import datetime
 
 def archive_index(request):
-    archive_type = request.site.preferences.date_archives
+    archive_type = config.archive.archive_type
     dates = Leaf.on_site.stream().dates('pub_date', archive_type, order='DESC')
     archives = []
     for d in dates:

File leaves/plugins/blog/feeds.py

View file
  • Ignore whitespace
 from django.utils.feedgenerator import Atom1Feed
 from django.shortcuts import get_object_or_404
 from leaves.plugins.blog.models import Post, Category
-from leaves.utils import get_site
+from leaves.utils import get_site, config
 from leaves.feeds import LeafItemFeed
 
 class PostItemFeed (LeafItemFeed):
         return '%s: Recent Posts' % site.name
 
     def items(self):
-        site = get_site()
-        return Post.on_site.active().filter(feed=True).order_by('-pub_date')[:site.preferences.feed_count]
+        return Post.on_site.active().filter(feed=True).order_by('-pub_date')[:config.feed_count]
 
 class CategoryFeed (PostItemFeed):
     feed_type = Atom1Feed
         return '%s: Recent posts in "%s"' % (site.name, obj.name)
 
     def items(self, obj):
-        site = get_site()
-        return Post.on_site.active().filter(categories=obj, feed=True).order_by('-pub_date')[:site.preferences.feed_count]
+        return Post.on_site.active().filter(categories=obj, feed=True).order_by('-pub_date')[:config.feed_count]

File leaves/plugins/twitter/admin.py

View file
  • Ignore whitespace
 from django.contrib import admin
 from leaves.plugins.twitter.models import Config
+from leaves.admin import ConfigAdmin
 
-admin.site.register(Config)
+admin.site.register(Config, ConfigAdmin)

File leaves/plugins/twitter/models.py

View file
  • Ignore whitespace
 from django.db import models
-from leaves.models import PluginConfig
+from leaves.models import SiteConfig
 
-class Config (PluginConfig):
+class Config (SiteConfig):
 	enabled = models.BooleanField(default=False)
 	screen_name = models.CharField(max_length=14, blank=True, default='')
 	display_count = models.PositiveIntegerField(default=5)

File leaves/plugins/twitter/templatetags/twitter.py

View file
  • Ignore whitespace
 TIMELINE_ENDPOINT = 'http://api.twitter.com/1/statuses/user_timeline.json'
 
 @register.inclusion_tag('twitter/feed.html')
-def twitter_feed(count=None):
-	if not config.twitter.enabled:
-		return {}
-	if count is None:
-		count = config.twitter.display_count
+def twitter_feed():
+	count = config.twitter.display_count
 	user_name = config.twitter.screen_name
 	cache_key = 'twitter_%s_%s' % (user_name, count)
 	data = cache.get(cache_key)

File leaves/themes/stream/templates/archive/stream.html

View file
  • Ignore whitespace
 {% block datenav %}
     <div class="box">
         <div class="title">Archive</div>
-        {% archive_dates site.preferences.date_archives current_date %}
+        {% archive_dates current_date %}
     </div>
 {% endblock %}

File leaves/themes/stream/templates/base.html

View file
  • Ignore whitespace
 </head>
 <body class="{% block section %}default{% endblock %}">
 <div id="header">
-    <div class="container">
-        <a class="title stroked" href="{% url homepage %}">{{ site.name }}</a>
-        {% block topnav %}
-        <ul class="page-list">
-            <li class="archive"><a href="{% url archive-index %}">Archive</a></li>
-            {% for p in leaves.pages.navigable_pages %}
-            <li{% ifequal p leaf %} class="selected"{% endifequal %}><a href="{{ p.get_url }}">{{ p }}</a></li>
-            {% endfor %}
-        </ul>
-        {% endblock %}
-    </div>
+	<div class="container">
+		<a class="title stroked" href="{% url homepage %}">{{ site.name }}</a>
+		{% block topnav %}
+		<ul class="page-list">
+			<li class="archive"><a href="{% url archive-index %}">Archive</a></li>
+			{% for p in leaves.pages.navigable_pages %}
+			<li{% ifequal p leaf %} class="selected"{% endifequal %}><a href="{{ p.get_url }}">{{ p }}</a></li>
+			{% endfor %}
+		</ul>
+		{% endblock %}
+	</div>
 </div>
 {% if messages %}
 <ul class="messages">
-        {% for message in messages %}
-        <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
-        {% endfor %}
+		{% for message in messages %}
+		<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
+		{% endfor %}
 </ul>
 {% endif %}
 <div id="container" class="container">
 	<div id="nav">
 	{% block blognav %}
 		<div class="box">
-		    <div class="title">Articles</div>
+			<div class="title">Articles</div>
 			{% navigation "blog" %}
 		</div>
 	{% endblock %}
 			{% navigation "photos" %}
 		</div>
 	{% endblock %}
-	<!--
-    {% block datenav %}
-       <div class="box">
-           <div class="title">Archive</div>
-           {% load archive %}
-           {% archive_dates site.preferences.date_archives %}
-       </div>
-    {% endblock %}
-    -->
-        <div class="box">
-            <div class="title">Twitter</div>
-            {% load twitter %}
-            {% twitter_feed 3 %}
-        </div>
+	{% block datenav %}
+	{% if config.archive.enabled and config.archive.nav_dates %}
+	   <div class="box">
+		   <div class="title">Archive</div>
+		   {% load archive %}
+		   {% archive_dates %}
+	   </div>
+	{% endif %}
+	{% endblock %}
+	{% if config.twitter.enabled %}
+		<div class="box">
+			<div class="title">Twitter</div>
+			{% load twitter %}
+			{% twitter_feed %}
+		</div>
+	{% endif %}
 		<div class="box">
 			<div class="title">Search</div>
 			<div class="padded">
 	<div style="clear:both;"></div>
 </div>
 {% block post-container %}{% endblock %}
+{% block analytics %}
+<script type="text/javascript">
+  var _gaq = _gaq || [];
+  _gaq.push(['_setAccount', 'UA-10897395-2']);
+  _gaq.push(['_trackPageview']);
+  (function() {
+	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+  })();
+</script>
+{% endblock %}
 </body>
 </html>

File leaves/utils.py

View file
  • Ignore whitespace
 from django.contrib.contenttypes.models import ContentType
 import os, datetime
 
-class PluginHelperProxy (object):
+class HelperProxy (object):
 
 	def __init__(self):
-		self.base = importlib.import_module('leaves.helpers')
+		self.plugins = [p.split('.')[-1] for p in settings.LEAVES_PLUGINS]
 
 	def __getattr__(self, name):
-		if hasattr(self.base, name):
-			return getattr(self.base, name)
-		try:
-			mod = models.get_app(name)
-			helper_name = mod.__package__ + '.helpers'
-			return importlib.import_module(helper_name)
-		except Exception, ex:
-			return None
+		if name in self.plugins:
+			try:
+				mod = models.get_app(name)
+				helper_name = mod.__package__ + '.helpers'
+				return importlib.import_module(helper_name)
+			except Exception, ex:
+				return None
+		else:
+			base = importlib.import_module('leaves.helpers')
+			return getattr(base, name)
 
-class NullConfig (object):
+class ConfigProxy (object):
+	
+	def __init__(self):
+		self.plugins = [p.split('.')[-1] for p in settings.LEAVES_PLUGINS]
+	
 	def __getattr__(self, name):
-		return None
+		site = get_site()
+		if name in self.plugins:
+			accessor_name = '%s_config' % name
+			try:
+				return getattr(site, accessor_name)
+			except ObjectDoesNotExist:
+				# Find the model class with the given relation to Site, and create an instance.
+				for r in site._meta.get_all_related_objects():
+					if r.get_accessor_name() == accessor_name:
+						return r.model.objects.create(site=site)
+				raise AttributeError('No config found for %s' % name)
+		else:
+			try:
+				return getattr(site.leaves_config, name)
+			except ObjectDoesNotExist:
+				from leaves.models import Preferences
+				prefs = Preferences.objects.create(site=site)
+				return getattr(prefs, name)
 
-class PluginConfigProxy (object):
-	def __getattr__(self, name):
-		try:
-			# TODO: cache configs, invalidate on PluginConfig.save
-			ct = ContentType.objects.get(app_label=name, model='config')
-			config_class = ct.model_class()
-			config_obj, created = config_class.objects.get_or_create(site=get_site())
-			return config_obj
-		except:
-			return NullConfig()
-
-config = PluginConfigProxy()
+helpers = HelperProxy()
+config = ConfigProxy()
 
 def filter_active_leaves(queryset):
 	"""
 	queryset.
 	"""
 	if per_page is None:
-		per_page = request.site.preferences.stream_count
+		per_page = config.stream_count
 	paginator = Paginator(queryset, per_page)
 	try:
 		pagenum = int(request.GET.get('page', '1'))
 		from leaves.middleware import request_context
 		return request_context.site
 	except:
-		return Site.objects.select_related('preferences').get(pk=settings.SITE_ID)
+		return Site.objects.select_related('leaves_config').get(pk=settings.SITE_ID)
 
 def get_theme_dir(theme_name):
 	"""
 	theme_static = settings.STATIC_URL
 	if not theme_static.endswith('/'):
 		theme_static += '/'
-	theme_static += request.site.preferences.theme + '/'
+	theme_static += config.theme + '/'
 	return {
-		'leaves': PluginHelperProxy(),
+		'leaves': helpers,
+		'config': config,
 		'site': request.site,
 		'THEME_STATIC_URL': theme_static,
 		'None': None,

File leaves/views.py

View file
  • Ignore whitespace
 from django.http import HttpResponse, Http404
 from leaves.models import Leaf, Tag, Attachment
 from leaves.forms import CommentForm
-from leaves.utils import get_page
+from leaves.utils import get_page, config
 import mimetypes
 import datetime
 import os
 		leaf.save(set_date=False)
 	comment_form = None
 	if leaf.allow_comments:
-		status = 'published' if request.user.is_authenticated() else request.site.preferences.default_comment_status
+		status = 'published' if request.user.is_authenticated() else config.default_comment_status
 		if request.method == 'POST':
 			try:
 				parent = leaf.comments.get(pk=request.POST['reply_to'])