Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

'flatblock' with default content feature #9

Open
wants to merge 10 commits into from

2 participants

@mandx

This references my previous issue.

See the commit message for changes, I used the syntax specified by @zerok

mandx/django-flatblocks@b233a39

Armando Pére... added some commits
Armando Pérez Marqués Added 'flatblock_default' template tag
This 'flatblock_default' template tag allows providing a default block of
text for the flatblock, and not using the slug for this. Also, the content
of the flatblock is ready-to-edit by final users, and allowing the site
builders to specify suitable (and even ready to use) default content.
a1273dd
Armando Pérez Marqués Revert "Added 'flatblock_default' template tag"
This reverts commit a1273dd.
ef6b5aa
Armando Pérez Marqués Rework of the default block content feature
Introduces a new parameter to the `flatblock` tag: 'with-default'. When
this parameter is present, the tag parses the template until the
`end_flatblock` tag is found, and everything between the tags is saved
for later rendering and used as default content for the FlatBlock
instance if it doesn't exists.

Also introduces two new settings:
`FLATBLOCKS_STRICT_DEFAULT_CHECK`: If True, when the tag founds a
Flatblock instance that matches the slug but its fields are empty,
the tag fields the instance's fields with the defaults values, if
provided.
`FLATBLOCKS_STRICT_DEFAULT_CHECK_UPDATE`: If True and the above
situation occurs then the instance is saved to the DB with the
defaults values.
b233a39
Armando Pérez Marqués Changes and tests:
- If a block name is specified in a template variable, and it is not
  allowed to autocreate blocks, but a default was specified, a dummy
  (unsaved) flatblock is created with the default values, and then
  rendered.
- The default cache timeout for flatblocks is specified as a setting,
  `FLATBLOCKS_CACHE_TIMEOUT`, and defaults to Django's cache timeout.
  This allows to specify different a timeout value than the default
  cache one, and without setting it on every template tag call.
- Added syntax check and tests for the case where more than one argument
  is passed to the templatetag after the `with-default` keyword.
- Miscelaneous tests
8848e6b
Armando Pérez Marqués Removed comment 06b4325
Armando Pérez Marqués Fixed DebugNodeList reference 0fe5b01
@timmyomahony

Came to suggest this feature - nice to see someone has done it themselves!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jun 15, 2011
  1. Added 'flatblock_default' template tag

    Armando Pérez Marqués authored
    This 'flatblock_default' template tag allows providing a default block of
    text for the flatblock, and not using the slug for this. Also, the content
    of the flatblock is ready-to-edit by final users, and allowing the site
    builders to specify suitable (and even ready to use) default content.
Commits on Jun 16, 2011
  1. Revert "Added 'flatblock_default' template tag"

    Armando Pérez Marqués authored
    This reverts commit a1273dd.
  2. Rework of the default block content feature

    Armando Pérez Marqués authored
    Introduces a new parameter to the `flatblock` tag: 'with-default'. When
    this parameter is present, the tag parses the template until the
    `end_flatblock` tag is found, and everything between the tags is saved
    for later rendering and used as default content for the FlatBlock
    instance if it doesn't exists.
    
    Also introduces two new settings:
    `FLATBLOCKS_STRICT_DEFAULT_CHECK`: If True, when the tag founds a
    Flatblock instance that matches the slug but its fields are empty,
    the tag fields the instance's fields with the defaults values, if
    provided.
    `FLATBLOCKS_STRICT_DEFAULT_CHECK_UPDATE`: If True and the above
    situation occurs then the instance is saved to the DB with the
    defaults values.
Commits on Aug 16, 2011
  1. Changes and tests:

    Armando Pérez Marqués authored
    - If a block name is specified in a template variable, and it is not
      allowed to autocreate blocks, but a default was specified, a dummy
      (unsaved) flatblock is created with the default values, and then
      rendered.
    - The default cache timeout for flatblocks is specified as a setting,
      `FLATBLOCKS_CACHE_TIMEOUT`, and defaults to Django's cache timeout.
      This allows to specify different a timeout value than the default
      cache one, and without setting it on every template tag call.
    - Added syntax check and tests for the case where more than one argument
      is passed to the templatetag after the `with-default` keyword.
    - Miscelaneous tests
Commits on Aug 17, 2011
  1. Removed comment

    Armando Pérez Marqués authored
Commits on Aug 19, 2011
  1. Fixed DebugNodeList reference

    Armando Pérez Marqués authored
Commits on Apr 19, 2012
  1. @mandx

    Space removal

    mandx authored
  2. @mandx
Commits on Apr 20, 2012
  1. @mandx

    Set my name

    mandx authored
  2. @mandx
This page is out of date. Refresh to see the latest.
View
5 flatblocks/admin.py
@@ -4,7 +4,8 @@
class FlatBlockAdmin(admin.ModelAdmin):
ordering = ['slug', ]
- list_display = ('slug', 'header')
- search_fields = ('slug', 'header', 'content')
+ list_display = ('slug', 'header', 'site', )
+ list_filter = ('site', )
+ search_fields = ('slug', 'header', 'content', 'site__domain', 'site__name', )
admin.site.register(FlatBlock, FlatBlockAdmin)
View
BIN  flatblocks/locale/de/LC_MESSAGES/django.mo
Binary file not shown
View
BIN  flatblocks/locale/no/LC_MESSAGES/django.mo
Binary file not shown
View
BIN  flatblocks/locale/ru/LC_MESSAGES/django.mo
Binary file not shown
View
55 flatblocks/migrations/0002_auto__add_field_flatblock_site__del_unique_flatblock_slug__add_unique_.py
@@ -0,0 +1,55 @@
+# -*- coding: 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):
+ # Removing unique constraint on 'FlatBlock', fields ['slug']
+ db.delete_unique('flatblocks_flatblock', ['slug'])
+
+ # Adding field 'FlatBlock.site'
+ db.add_column('flatblocks_flatblock', 'site',
+ self.gf('django.db.models.fields.related.ForeignKey')(default=1, related_name='flatblocks', to=orm['sites.Site']),
+ keep_default=False)
+
+ # Adding index on 'FlatBlock', fields ['slug']
+ db.create_index('flatblocks_flatblock', ['slug'])
+
+ # Adding unique constraint on 'FlatBlock', fields ['slug', 'site']
+ db.create_unique('flatblocks_flatblock', ['slug', 'site_id'])
+
+ def backwards(self, orm):
+ # Removing unique constraint on 'FlatBlock', fields ['slug', 'site']
+ db.delete_unique('flatblocks_flatblock', ['slug', 'site_id'])
+
+ # Removing index on 'FlatBlock', fields ['slug']
+ db.delete_index('flatblocks_flatblock', ['slug'])
+
+ # Deleting field 'FlatBlock.site'
+ db.delete_column('flatblocks_flatblock', 'site_id')
+
+ # Adding unique constraint on 'FlatBlock', fields ['slug']
+ db.create_unique('flatblocks_flatblock', ['slug'])
+
+ models = {
+ 'flatblocks.flatblock': {
+ 'Meta': {'unique_together': "(('slug', 'site'),)", 'object_name': 'FlatBlock'},
+ 'content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+ 'header': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flatblocks'", 'to': "orm['sites.Site']"}),
+ 'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
+ },
+ 'sites.site': {
+ 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
+ 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+ }
+ }
+
+ complete_apps = ['flatblocks']
View
15 flatblocks/models.py
@@ -1,3 +1,4 @@
+from django.contrib.sites.models import Site
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
@@ -11,7 +12,7 @@ class FlatBlock(models.Model):
basically a piece of content with a given name (slug) and an optional
title (header) which you can, for example, use in a sidebar of a website.
"""
- slug = models.CharField(max_length=255, unique=True,
+ slug = models.CharField(max_length=255, db_index=True,
verbose_name=_('Slug'),
help_text=_("A unique name used for reference in the templates"))
header = models.CharField(blank=True, null=True, max_length=255,
@@ -19,6 +20,14 @@ class FlatBlock(models.Model):
help_text=_("An optional header for this content"))
content = models.TextField(verbose_name=_('Content'), blank=True,
null=True)
+ site = models.ForeignKey(Site, related_name='flatblocks', verbose_name=_('Site'))
+
+ class Meta:
+ verbose_name = _('Flat block')
+ verbose_name_plural = _('Flat blocks')
+ unique_together = (
+ ('slug', 'site', ),
+ )
def __unicode__(self):
return u"%s" % (self.slug,)
@@ -27,7 +36,3 @@ def save(self, *args, **kwargs):
super(FlatBlock, self).save(*args, **kwargs)
# Now also invalidate the cache used in the templatetag
cache.delete('%s%s' % (CACHE_PREFIX, self.slug, ))
-
- class Meta:
- verbose_name = _('Flat block')
- verbose_name_plural = _('Flat blocks')
View
8 flatblocks/settings.py
@@ -1,5 +1,13 @@
from django.conf import settings
+from django.core.cache import cache
CACHE_PREFIX = getattr(settings, 'FLATBLOCKS_CACHE_PREFIX', 'flatblocks_')
AUTOCREATE_STATIC_BLOCKS = getattr(settings,
'FLATBLOCKS_AUTOCREATE_STATIC_BLOCKS', False)
+
+STRICT_DEFAULT_CHECK = getattr(settings,
+ 'FLATBLOCKS_STRICT_DEFAULT_CHECK', False)
+STRICT_DEFAULT_CHECK_UPDATE = getattr(settings,
+ 'FLATBLOCKS_STRICT_DEFAULT_CHECK_UPDATE', False)
+
+CACHE_TIMEOUT = getattr(settings, 'FLATBLOCKS_CACHE_TIMEOUT', cache.default_timeout)
View
159 flatblocks/templatetags/flatblock_tags.py
@@ -42,11 +42,14 @@
"""
from django import template
-from django.template import loader
-from django.db import models
+from django.contrib.sites.models import Site
from django.core.cache import cache
+# from django.db import models
+from django.template import loader
+from django.template import debug as template_debug
from flatblocks import settings
+from flatblocks.models import FlatBlock
import logging
@@ -54,7 +57,6 @@
register = template.Library()
logger = logging.getLogger(__name__)
-FlatBlock = models.get_model('flatblocks', 'flatblock')
class BasicFlatBlockWrapper(object):
def prepare(self, parser, token):
@@ -73,6 +75,16 @@ def prepare(self, parser, token):
self.cache_time = 0
self.tpl_name = None
tag_name, self.slug, args = tokens[0], tokens[1], tokens[2:]
+
+ try:
+ # Split the arguments in two sections, the "core" ones
+ # and the ones for default content feature
+ with_index = args.index('with-default')
+ default_args = args[with_index:]
+ args = args[:with_index]
+ except ValueError:
+ default_args = []
+
num_args = len(args)
if num_args == 0:
# Only the block name was specified
@@ -90,6 +102,39 @@ def prepare(self, parser, token):
self.tpl_name = args[2]
else:
raise template.TemplateSyntaxError, "%r tag should have between 1 and 4 arguments" % (tokens[0],)
+
+ if len(default_args) > 0:
+ # If we got arguments for default content, or, at least, the
+ # 'with-default' token was specified, parse until the end of
+ # the closing tag, and keep the parsed nodelist for later
+ # rendering
+ end_tag_name = 'end_%s' % tag_name
+ self.inner_nodelist = parser.parse((end_tag_name, ))
+ parser.delete_first_token()
+
+ if len(default_args) > 2:
+ raise template.TemplateSyntaxError(
+ u'Too many arguments for this block header')
+
+ # If an argument was specified after 'with-default', it is used
+ # as the flatblock's header
+
+ if len(default_args) == 2:
+ self.default_header = default_args[1]
+ if self.default_header[0] == self.default_header[-1] and \
+ self.default_header[0] in ('"', "'"):
+ self.default_header = self.default_header[1:-1]
+ self.default_header_is_variable = False
+ else:
+ self.default_header_is_variable = True
+ else:
+ self.default_header = None
+ self.default_header_is_variable = False
+ else:
+ self.default_header = None
+ self.default_header_is_variable = False
+ self.inner_nodelist = None
+
# Check to see if the slug is properly double/single quoted
if not (self.slug[0] == self.slug[-1] and self.slug[0] in ('"', "'")):
self.is_variable = True
@@ -108,19 +153,29 @@ def __call__(self, parser, token):
self.prepare(parser, token)
return FlatBlockNode(self.slug, self.is_variable, self.cache_time,
template_name=self.tpl_name,
- tpl_is_variable=self.tpl_is_variable)
+ tpl_is_variable=self.tpl_is_variable,
+ default_header=self.default_header,
+ default_header_is_variable=self.default_header_is_variable,
+ default_content=self.inner_nodelist)
class PlainFlatBlockWrapper(BasicFlatBlockWrapper):
def __call__(self, parser, token):
self.prepare(parser, token)
- return FlatBlockNode(self.slug, self.is_variable, self.cache_time, False)
+ return FlatBlockNode(
+ self.slug, self.is_variable, self.cache_time, False,
+ default_header=self.default_header,
+ default_header_is_variable=self.default_header_is_variable,
+ default_content=self.inner_nodelist,
+ )
do_get_flatblock = BasicFlatBlockWrapper()
do_plain_flatblock = PlainFlatBlockWrapper()
class FlatBlockNode(template.Node):
def __init__(self, slug, is_variable, cache_time=0, with_template=True,
- template_name=None, tpl_is_variable=False):
+ template_name=None, tpl_is_variable=False,
+ default_header=None, default_header_is_variable=None,
+ default_content=None):
if template_name is None:
self.template_name = 'flatblocks/flatblock.html'
else:
@@ -133,43 +188,97 @@ def __init__(self, slug, is_variable, cache_time=0, with_template=True,
self.cache_time = cache_time
self.with_template = with_template
+ self.default_header_is_variable = default_header_is_variable
+ self.default_header = template.Variable(default_header)\
+ if default_header_is_variable \
+ else default_header
+ self.default_content = default_content
+
def render(self, context):
+ current_site = Site.objects.get_current()
if self.is_variable:
real_slug = template.Variable(self.slug).resolve(context)
else:
real_slug = self.slug
+
if isinstance(self.template_name, template.Variable):
real_template = self.template_name.resolve(context)
else:
real_template = self.template_name
+
+ if isinstance(self.default_header, template.Variable):
+ real_default_header = self.default_header.resolve(context)
+ else:
+ real_default_header = self.default_header
+
+ if isinstance(self.default_content,
+ (template.NodeList, template_debug.DebugNodeList)):
+ real_default_contents = self.default_content.render(context)
+ else:
+ real_default_contents = self.default_content
+
# Eventually we want to pass the whole context to the template so that
# users have the maximum of flexibility of what to do in there.
if self.with_template:
- new_ctx = template.Context({})
+ new_ctx = template.Context()
new_ctx.update(context)
+ else:
+ new_ctx = None
+
try:
flatblock = None
if self.cache_time != 0:
cache_key = settings.CACHE_PREFIX + real_slug
flatblock = cache.get(cache_key)
+
if flatblock is None:
+ flatblock_created = False
# if flatblock's slug is hard-coded in template then it is
# safe and convenient to auto-create block if it doesn't exist.
# This behaviour can be configured using the
# FLATBLOCKS_AUTOCREATE_STATIC_BLOCKS setting
if self.is_variable or not settings.AUTOCREATE_STATIC_BLOCKS:
- flatblock = FlatBlock.objects.get(slug=real_slug)
+ flatblock = FlatBlock.objects.get(slug=real_slug, site=current_site)
else:
- flatblock, _ = FlatBlock.objects.get_or_create(
- slug=real_slug,
- defaults = {'content': real_slug}
- )
+ # try:
+ # flatblock = FlatBlock.objects.get(slug=real_slug, site=current_site)
+ # except FlatBlock.DoesNotExist:
+ # flatblock = FlatBlock.objects.create(
+ # slug=real_slug,
+ # content=real_default_contents or real_slug,
+ # header=real_default_header,
+ # site=current_site
+ # )
+ # flatblock.save()
+ # flatblock_created = True
+ flatblock, flatblock_created = FlatBlock.objects.get_or_create(
+ slug=real_slug, site=current_site, defaults={
+ 'content': real_default_contents or real_slug,
+ 'header': real_default_header,
+ }
+ )
+
+ # If the flatblock exists, but its fields are empty, and
+ # the STRICT_DEFAULT_CHECK is True, then update the fields
+ # with the default contents.
+ flatblock_updated = False
+ if not flatblock_created and settings.STRICT_DEFAULT_CHECK:
+ if not flatblock.header and not real_default_header is None:
+ flatblock.header = real_default_header
+ flatblock_updated = True
+ if not flatblock.content and self.default_content:
+ flatblock.content = real_default_contents or real_slug
+ flatblock_updated = True
+
+ if flatblock_updated and settings.STRICT_DEFAULT_CHECK_UPDATE:
+ flatblock.save()
+
if self.cache_time != 0:
if self.cache_time is None or self.cache_time == 'None':
logger.debug("Caching %s for the cache's default timeout"
% (real_slug,))
- cache.set(cache_key, flatblock)
+ cache.set(cache_key, flatblock, settings.CACHE_TIMEOUT)
else:
logger.debug("Caching %s for %s seconds" % (real_slug,
str(self.cache_time)))
@@ -177,14 +286,26 @@ def render(self, context):
else:
logger.debug("Don't cache %s" % (real_slug,))
- if self.with_template:
- tmpl = loader.get_template(real_template)
- new_ctx.update({'flatblock':flatblock})
- return tmpl.render(new_ctx)
- else:
- return flatblock.content
+ return self.flatblock_output(real_template, flatblock, new_ctx)
except FlatBlock.DoesNotExist:
+ if real_default_contents:
+ flatblock = FlatBlock(
+ slug=real_slug,
+ content=real_default_contents,
+ header=real_default_header,
+ site=current_site,
+ )
+ return self.flatblock_output(real_template, flatblock, new_ctx)
return ''
+ def flatblock_output(self, template_name, flatblock, context=None):
+ if not self.with_template:
+ return flatblock.content
+ tmpl = loader.get_template(template_name)
+ context = context or {}
+ context.update({'flatblock': flatblock, })
+ return tmpl.render(template.Context(context))
+
+
register.tag('flatblock', do_get_flatblock)
register.tag('plain_flatblock', do_plain_flatblock)
View
297 flatblocks/tests.py
@@ -2,6 +2,7 @@
from django.test import TestCase
from django.core.cache import cache
from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
from django import db
from flatblocks.models import FlatBlock
@@ -15,7 +16,8 @@ def setUp(self):
self.testblock = FlatBlock.objects.create(
slug='block',
header='HEADER',
- content='CONTENT'
+ content='CONTENT',
+ site=Site.objects.get_current(),
)
self.admin = User.objects.create_superuser('admin', 'admin@localhost', 'adminpwd')
@@ -34,7 +36,7 @@ def testCacheReset(self):
Tests if FlatBlock.save() resets the cache.
"""
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" 60 %}')
- tpl.render(template.Context({}))
+ tpl.render(template.Context())
name = '%sblock' % settings.CACHE_PREFIX
self.assertNotEquals(None, cache.get(name))
block = FlatBlock.objects.get(slug='block')
@@ -55,17 +57,18 @@ def setUp(self):
self.testblock = FlatBlock.objects.create(
slug='block',
header='HEADER',
- content='CONTENT'
+ content='CONTENT',
+ site=Site.objects.get_current(),
)
def testLoadingTaglib(self):
"""Tests if the taglib defined in this app can be loaded"""
tpl = template.Template('{% load flatblock_tags %}')
- tpl.render(template.Context({}))
+ tpl.render(template.Context())
def testExistingPlain(self):
tpl = template.Template('{% load flatblock_tags %}{% plain_flatblock "block" %}')
- self.assertEqual(u'CONTENT', tpl.render(template.Context({})).strip())
+ self.assertEqual(u'CONTENT', tpl.render(template.Context()).strip())
def testExistingTemplate(self):
expected = """<div class="flatblock block-block">
@@ -76,22 +79,22 @@ def testExistingTemplate(self):
</div>
"""
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" %}')
- self.assertEqual(expected, tpl.render(template.Context({})))
+ self.assertEqual(expected, tpl.render(template.Context()))
def testUsingMissingTemplate(self):
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" using "missing_template.html" %}')
- exception = template.TemplateSyntaxError
- self.assertRaises(exception, tpl.render, template.Context({}))
+ exception = template.TemplateDoesNotExist
+ self.assertRaises(exception, tpl.render, template.Context())
def testSyntax(self):
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" %}')
- tpl.render(template.Context({}))
+ tpl.render(template.Context())
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" 123 %}')
- tpl.render(template.Context({}))
+ tpl.render(template.Context())
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" using "flatblocks/flatblock.html" %}')
- tpl.render(template.Context({}))
+ tpl.render(template.Context())
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" 123 using "flatblocks/flatblock.html" %}')
- tpl.render(template.Context({}))
+ tpl.render(template.Context())
def testBlockAsVariable(self):
tpl = template.Template('{% load flatblock_tags %}{% flatblock blockvar %}')
@@ -100,6 +103,11 @@ def testBlockAsVariable(self):
class AutoCreationTest(TestCase):
""" Test case for block autcreation """
+ def setUp(self):
+ self.old_AUTOCREATE_STATIC_BLOCKS = settings.AUTOCREATE_STATIC_BLOCKS
+
+ def tearDown(self):
+ settings.AUTOCREATE_STATIC_BLOCKS = self.old_AUTOCREATE_STATIC_BLOCKS
def testMissingStaticBlock(self):
"""Tests if a missing block with hardcoded name will be auto-created"""
@@ -108,18 +116,17 @@ def testMissingStaticBlock(self):
<div class="content">foo</div>
</div>"""
settings.AUTOCREATE_STATIC_BLOCKS = True
+ self.assertEqual(FlatBlock.objects.filter(slug='foo').count(), 0)
tpl = template.Template('{% load flatblock_tags %}{% flatblock "foo" %}')
- self.assertEqual(expected, tpl.render(template.Context({})).strip())
- self.assertEqual(FlatBlock.objects.count(), 1)
- self.assertEqual(expected, tpl.render(template.Context({})).strip())
- self.assertEqual(FlatBlock.objects.count(), 1)
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+ self.assertEqual(FlatBlock.objects.filter(slug='foo').count(), 1)
def testNotAutocreatedMissingStaticBlock(self):
"""Tests if a missing block with hardcoded name won't be auto-created if feature is disabled"""
expected = u""
settings.AUTOCREATE_STATIC_BLOCKS = False
tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" %}')
- self.assertEqual(expected, tpl.render(template.Context({})).strip())
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
self.assertEqual(FlatBlock.objects.filter(slug='block').count(), 0)
def testMissingVariableBlock(self):
@@ -128,4 +135,260 @@ def testMissingVariableBlock(self):
tpl = template.Template('{% load flatblock_tags %}{% flatblock name %}')
self.assertEqual('', tpl.render(template.Context({'name': 'foo'})).strip())
+class TagDefaultTests(TestCase):
+ def setUp(self):
+ FlatBlock.objects.all().delete()
+ self.old_AUTOCREATE_STATIC_BLOCKS = settings.AUTOCREATE_STATIC_BLOCKS
+
+ def tearDown(self):
+ settings.AUTOCREATE_STATIC_BLOCKS = self.old_AUTOCREATE_STATIC_BLOCKS
+
+ def testTagDefault(self):
+ expected = u"""<div class="flatblock block-block_default">
+
+ <div class="content">This is the default content</div>
+</div>"""
+
+ settings.AUTOCREATE_STATIC_BLOCKS = True
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" with-default %}This is the default content{% end_flatblock %}')
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+ FlatBlock.objects.get(slug='block_default').delete()
+
+ def testTagPlainDefault(self):
+ settings.AUTOCREATE_STATIC_BLOCKS = True
+ qs = FlatBlock.objects.filter(slug='block_default')
+ self.assertEqual(0, qs.count())
+ tpl = template.Template('{% load flatblock_tags %}{% plain_flatblock "block_default" with-default %}This is the default content{% end_plain_flatblock %}')
+ self.assertEqual(u'This is the default content', tpl.render(template.Context()).strip())
+ self.assertEqual(1, qs.count())
+ self.assertEqual(u'This is the default content', qs[0].content)
+ self.assertEqual(None, qs[0].header)
+ qs.delete()
+
+ def testUsingMissingTemplate(self):
+ settings.AUTOCREATE_STATIC_BLOCKS = True
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" using "missing_template.html" with-default %}This is the default content{% end_flatblock %}')
+ self.assertRaises(template.TemplateDoesNotExist, tpl.render, template.Context())
+
+ def testSyntax(self):
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" with-default %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" 123 with-default %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" using "flatblocks/flatblock.html" with-default %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" 123 using "flatblocks/flatblock.html" with-default %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" with-default "header_default" %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" 123 with-default "header_default" %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" using "flatblocks/flatblock.html" with-default "header_default" %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" 123 using "flatblocks/flatblock.html" with-default "header_default" %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context())
+
+ self.assertRaises(template.TemplateSyntaxError, template.Template, '{% load flatblock_tags %}{% flatblock "block_default" with-default header default %}This is the default content{% end_flatblock %}')
+ self.assertRaises(template.TemplateSyntaxError, template.Template, '{% load flatblock_tags %}{% flatblock "block_default" with-default "header" "default" %}This is the default content{% end_flatblock %}')
+
+ def testBlockAsVariable(self):
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock blockvar with-default %}This is the default content{% end_flatblock %}')
+ tpl.render(template.Context({'blockvar': 'block_default'}))
+
+ def testTagDefault_AutoCreate(self):
+ block_content = 'This is the default content of block new1'
+ block_slug = 'block_default_new1'
+ expected = u"""<div class="flatblock block-%(block_slug)s">
+
+ <div class="content">%(block_content)s</div>
+</div>""" % {'block_content': block_content, 'block_slug': block_slug}
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \
+ block_slug + '" with-default %}' + block_content + \
+ '{% end_flatblock %}')
+
+ settings.AUTOCREATE_STATIC_BLOCKS = True
+
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+
+ flatblock = FlatBlock.objects.get(slug=block_slug)
+ self.assertEqual(flatblock.content, block_content)
+
+ def testTagDefault_AutoCreateWithHeader(self):
+ block_header = 'Header of block new2'
+ block_content = 'This is the default content of block new2'
+ block_slug = 'block_default_new2'
+ expected = u"""<div class="flatblock block-%(block_slug)s">
+
+ <h2 class="title">%(block_header)s</h2>
+
+ <div class="content">%(block_content)s</div>
+</div>""" % {'block_content': block_content,
+ 'block_slug': block_slug,
+ 'block_header': block_header}
+ tpl = template.Template(
+ '{% load flatblock_tags %}{% flatblock "' + block_slug + \
+ '" with-default "' + block_header + '" %}' + block_content + \
+ '{% end_flatblock %}')
+
+ old_setting = settings.AUTOCREATE_STATIC_BLOCKS
+ settings.AUTOCREATE_STATIC_BLOCKS = True
+
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+
+ flatblock = FlatBlock.objects.get(slug=block_slug)
+ self.assertEqual(flatblock.content, block_content)
+ self.assertEqual(flatblock.header, block_header)
+
+ settings.AUTOCREATE_STATIC_BLOCKS = old_setting
+
+ def testTagDefault_AutoCreateWithHeaderAsVar(self):
+ block_header = 'Header of block new3'
+ block_content = 'This is the default content of block new3'
+ block_slug = 'block_default_new3'
+ expected = u"""<div class="flatblock block-%(block_slug)s">
+
+ <h2 class="title">%(block_header)s</h2>
+
+ <div class="content">%(block_content)s</div>
+</div>""" % {'block_content': block_content, 'block_slug': block_slug,
+ 'block_header': block_header}
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \
+ block_slug + '" with-default header_var %}' + \
+ block_content + \
+ '{% end_flatblock %}')
+
+ old_setting = settings.AUTOCREATE_STATIC_BLOCKS
+ settings.AUTOCREATE_STATIC_BLOCKS = True
+
+ self.assertEqual(expected, tpl.render(template.Context({
+ 'header_var': block_header, })).strip())
+
+ flatblock = FlatBlock.objects.get(slug=block_slug)
+ self.assertEqual(flatblock.content, block_content)
+ self.assertEqual(flatblock.header, block_header)
+
+ settings.AUTOCREATE_STATIC_BLOCKS = old_setting
+
+ def testTagDefault_DontAutoCreate(self):
+ block_content = 'This is the default content of block new4'
+ block_slug = 'block_default_new4'
+
+ expected = u'<div class="flatblock block-' + block_slug + '">' + \
+ '\n\n <div class="content">' + block_content + \
+ '</div>\n</div>'
+
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \
+ block_slug + '" with-default %}' + block_content + \
+ '{% end_flatblock %}')
+
+ settings.AUTOCREATE_STATIC_BLOCKS = False
+
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+ self.assertEqual(FlatBlock.objects.filter(slug=block_slug).count(), 0)
+
+ def testTagDefault_TestExistingAutoCreate(self):
+ block_slug = 'block_existing'
+
+ testblock = FlatBlock.objects.create(
+ slug=block_slug,
+ header='HEADER_OF_SAVED_BLOCK',
+ content='CONTENT_OF_SAVED_BLOCK',
+ site=Site.objects.get_current(),
+ )
+
+ block_content = 'This is the new content of "block_existing"'
+ block_header = 'This is the new header of "block_existing"'
+
+ expected = u'<div class="flatblock block-block_existing">\n\n ' + \
+ '<h2 class="title">HEADER_OF_SAVED_BLOCK</h2>\n\n ' + \
+ '<div class="content">CONTENT_OF_SAVED_BLOCK</div>\n</div>'
+
+ tpl = template.Template(
+ '{% load flatblock_tags %}{% flatblock "' + block_slug + \
+ '" with-default "' + block_header + '" %}' + block_content + \
+ '{% end_flatblock %}')
+
+ settings.AUTOCREATE_STATIC_BLOCKS = True
+
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+ qs = FlatBlock.objects.filter(slug=block_slug)
+ self.assertEqual(qs.count(), 1)
+ self.assertEqual(testblock.header, qs[0].header)
+ self.assertEqual(testblock.content, qs[0].content)
+
+ def testTagDefault_CheckStrictFieldsNoUpdate(self):
+ block_header = 'Header of block NEW 5'
+ block_content = 'This is the content of block new 5'
+ block_slug = 'block_default_NEW5'
+
+ flatblock = FlatBlock.objects.create(
+ slug=block_slug, site=Site.objects.get_current())
+
+ expected = u"""<div class="flatblock block-%(block_slug)s">
+
+ <h2 class="title">%(block_header)s</h2>
+
+ <div class="content">%(block_content)s</div>
+</div>""" % {'block_content': block_content, 'block_slug': block_slug,
+ 'block_header': block_header}
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \
+ block_slug + '" with-default "' + \
+ block_header + '" %}' + block_content + \
+ '{% end_flatblock %}')
+
+ old_setting_autocreate = settings.AUTOCREATE_STATIC_BLOCKS
+ old_setting_strictcheck = settings.STRICT_DEFAULT_CHECK
+ old_setting_strictcheckupdate = settings.STRICT_DEFAULT_CHECK_UPDATE
+ settings.STRICT_DEFAULT_CHECK = True
+ settings.STRICT_DEFAULT_CHECK_UPDATE = False
+ settings.AUTOCREATE_STATIC_BLOCKS = False
+
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+
+ flatblock = FlatBlock.objects.get(slug=block_slug)
+ self.assertEqual(flatblock.content, None)
+ self.assertEqual(flatblock.header, None)
+
+ settings.AUTOCREATE_STATIC_BLOCKS = old_setting_autocreate
+ settings.STRICT_DEFAULT_CHECK = old_setting_strictcheck
+ settings.STRICT_DEFAULT_CHECK_UPDATE = old_setting_strictcheckupdate
+
+ def testTagDefault_CheckStrictFieldsDoUpdate(self):
+ block_header = 'Header of block NEW 6 '
+ block_content = 'This is the content of block new 6'
+ block_slug = 'block_default_NEW6'
+
+ flatblock = FlatBlock.objects.create(
+ slug=block_slug,
+ site=Site.objects.get_current()
+ )
+
+ expected = u"""<div class="flatblock block-%(block_slug)s">
+
+ <h2 class="title">%(block_header)s</h2>
+
+ <div class="content">%(block_content)s</div>
+</div>""" % {'block_content': block_content, 'block_slug': block_slug,
+ 'block_header': block_header}
+ tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \
+ block_slug + '" with-default "' + \
+ block_header + '" %}' + block_content + \
+ '{% end_flatblock %}')
+
+ old_setting_autocreate = settings.AUTOCREATE_STATIC_BLOCKS
+ old_setting_strictcheck = settings.STRICT_DEFAULT_CHECK
+ old_setting_strictcheckupdate = settings.STRICT_DEFAULT_CHECK_UPDATE
+ settings.STRICT_DEFAULT_CHECK = True
+ settings.STRICT_DEFAULT_CHECK_UPDATE = True
+ settings.AUTOCREATE_STATIC_BLOCKS = False
+
+ self.assertEqual(expected, tpl.render(template.Context()).strip())
+
+ flatblock = FlatBlock.objects.get(slug=block_slug)
+ self.assertEqual(flatblock.content, block_content)
+ self.assertEqual(flatblock.header, block_header)
+ settings.AUTOCREATE_STATIC_BLOCKS = old_setting_autocreate
+ settings.STRICT_DEFAULT_CHECK = old_setting_strictcheck
+ settings.STRICT_DEFAULT_CHECK_UPDATE = old_setting_strictcheckupdate
View
15 setup.py
@@ -1,3 +1,6 @@
+# -*- coding: utf-8 -*-
+
+from os import path
try:
from setuptools import setup, find_packages
except:
@@ -5,18 +8,20 @@
use_setuptools()
from setuptools import setup, find_packages
+README_RST = path.join(path.dirname(__file__), 'README.rst')
+
setup(
name = 'django-flatblocks',
- version = '0.6.0',
+ version = '0.7.0',
description = 'django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
- long_description = open('README.rst').read(),
+ long_description = open(README_RST).read(),
keywords = 'django apps',
license = 'New BSD License',
- author = 'Horst Gutmann',
- author_email = 'zerok@zerokspot.com',
- url = 'http://github.com/zerok/django-flatblocks/',
+ author = u'Armando Pérez (Horst Gutmann)',
+ # author_email = 'zerok@zerokspot.com',
+ url = 'http://github.com/mandx/django-flatblocks/',
dependency_links = [],
classifiers = [
'Development Status :: 3 - Alpha',
View
15 test_project/settings.py
@@ -9,13 +9,24 @@
DEBUG=True
TEMPLATE_DEBUG=True
-DATABASE_ENGINE = 'sqlite3'
-DATABASE_NAME = '/tmp/flatblocks.db'
+# DATABASE_ENGINE = 'sqlite3'
+# DATABASE_NAME = '/tmp/flatblocks.db'
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': '/tmp/flatblocks.db',
+ }
+}
+
+SITE_ID = 1
+
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
+ 'django.contrib.sites',
'flatblocks',
'south'
)
Something went wrong with that request. Please try again.