From a1273dd2b3b138845a2918406b10554c6556ecfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20P=C3=A9rez=20Marqu=C3=A9s?= Date: Wed, 15 Jun 2011 15:43:37 -0400 Subject: [PATCH 1/9] 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. --- flatblocks/templatetags/flatblock_tags.py | 144 ++++++++++++++++++++++ flatblocks/tests.py | 77 ++++++++++++ 2 files changed, 221 insertions(+) diff --git a/flatblocks/templatetags/flatblock_tags.py b/flatblocks/templatetags/flatblock_tags.py index 6b353e0..e9c4280 100644 --- a/flatblocks/templatetags/flatblock_tags.py +++ b/flatblocks/templatetags/flatblock_tags.py @@ -188,3 +188,147 @@ def render(self, context): register.tag('flatblock', do_get_flatblock) register.tag('plain_flatblock', do_plain_flatblock) + + +class FlatBlockDefaultWrapper(object): + def __init__(self, end_tag_name): + self.end_tag_name = end_tag_name + super(FlatBlockDefaultWrapper, self).__init__() + + def prepare(self, parser, token): + """ + The parser checks for following tag-configurations:: + + {% flatblock_default {block} %}{% end_flatblock_default %} + {% flatblock_default {block} {timeout} %}{% end_flatblock_default %} + {% flatblock_default {block} using {tpl_name} %}{% end_flatblock_default %} + {% flatblock_default {block} {timeout} using {tpl_name} %}{% end_flatblock_default %} + """ + self.inner_nodelist = parser.parse((self.end_tag_name, )) + parser.delete_first_token() + + tokens = token.split_contents() + self.is_variable = False + self.tpl_is_variable = False + self.slug = None + self.cache_time = 0 + self.tpl_name = None + tag_name, self.slug, args = tokens[0], tokens[1], tokens[2:] + num_args = len(args) + if num_args == 0: + # Only the block name was specified + pass + elif num_args == 1: + # block and timeout + self.cache_time = args[0] + pass + elif num_args == 2: + # block, "using", tpl_name + self.tpl_name = args[1] + elif num_args == 3: + # block, timeout, "using", tpl_name + self.cache_time = args[0] + self.tpl_name = args[2] + else: + raise template.TemplateSyntaxError, "%r tag should have between 1 and 4 arguments" % (tokens[0],) + # 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 + else: + self.slug = self.slug[1:-1] + # Clean up the template name + if self.tpl_name is not None: + if not(self.tpl_name[0] == self.tpl_name[-1] and self.tpl_name[0] in ('"', "'")): + self.tpl_is_variable = True + else: + self.tpl_name = self.tpl_name[1:-1] + if self.cache_time is not None and self.cache_time != 'None': + self.cache_time = int(self.cache_time) + + def __call__(self, parser, token): + self.prepare(parser, token) + return FlatBlockDefaultNode(self.slug, self.is_variable, + self.inner_nodelist, self.cache_time, + template_name=self.tpl_name, + tpl_is_variable=self.tpl_is_variable) + +class FlatBlockDefaultNode(template.Node): + def __init__(self, slug, is_variable, inner_nodelist, cache_time=0, + with_template=True, template_name=None, tpl_is_variable=False): + if template_name is None: + self.template_name = 'flatblocks/flatblock.html' + else: + if tpl_is_variable: + self.template_name = template.Variable(template_name) + else: + self.template_name = template_name + self.slug = slug + self.is_variable = is_variable + self.inner_nodelist = inner_nodelist + self.cache_time = cache_time + self.with_template = with_template + + def render(self, context): + 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 + # 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.update(context) + try: + flatblock = None + if self.cache_time != 0: + cache_key = settings.CACHE_PREFIX + real_slug + flatblock = cache.get(cache_key) + if flatblock is None: + + # 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) + else: + flatblock, _ = FlatBlock.objects.get_or_create( + slug=real_slug, + defaults = { 'content': self.inner_nodelist.render(context) }) + + 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) + else: + logger.debug("Caching %s for %s seconds" % (real_slug, + str(self.cache_time))) + cache.set(cache_key, flatblock, int(self.cache_time)) + 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 + except FlatBlock.DoesNotExist: + return '' + +class PlainFlatBlockDefaultWrapper(FlatBlockDefaultWrapper): + def __call__(self, parser, token): + self.prepare(parser, token) + return FlatBlockDefaultNode(self.slug, self.is_variable, self.inner_nodelist, self.cache_time, False) + +do_get_flatblock = FlatBlockDefaultWrapper('end_flatblock_default') +do_plain_flatblock = PlainFlatBlockDefaultWrapper('end_plain_flatblock_default') + +register.tag('flatblock_default', do_get_flatblock) +register.tag('plain_flatblock_default', do_plain_flatblock) + diff --git a/flatblocks/tests.py b/flatblocks/tests.py index b12b96f..3b6510f 100644 --- a/flatblocks/tests.py +++ b/flatblocks/tests.py @@ -129,3 +129,80 @@ def testMissingVariableBlock(self): self.assertEqual('', tpl.render(template.Context({'name': 'foo'})).strip()) +class TagDefaultTests(TestCase): + def setUp(self): + self.testblock = FlatBlock.objects.create( + slug='block_default', + header='HEADER', + content='CONTENT_DEFAULT' + ) + + def testTagDefault(self): + expected = u"""
+ +

HEADER

+ +
CONTENT_DEFAULT
+
""" + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" %}This is the default content{% end_flatblock_default %}') + self.assertEqual(expected, tpl.render(template.Context({})).strip()) + + def testTagPlainDefault(self): + tpl = template.Template('{% load flatblock_tags %}{% plain_flatblock_default "block_default" %}This is the default content{% end_plain_flatblock_default %}') + self.assertEqual(u'CONTENT_DEFAULT', tpl.render(template.Context({})).strip()) + + def testUsingMissingTemplate(self): + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" using "missing_template.html" %}This is the default content{% end_flatblock_default %}') + exception = template.TemplateSyntaxError + self.assertRaises(exception, tpl.render, template.Context({})) + + def testSyntax(self): + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" %}This is the default content{% end_flatblock_default %}') + tpl.render(template.Context({})) + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" 123 %}This is the default content{% end_flatblock_default %}') + tpl.render(template.Context({})) + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" using "flatblocks/flatblock.html" %}This is the default content{% end_flatblock_default %}') + tpl.render(template.Context({})) + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" 123 using "flatblocks/flatblock.html" %}This is the default content{% end_flatblock_default %}') + tpl.render(template.Context({})) + + def testBlockAsVariable(self): + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default blockvar %}This is the default content{% end_flatblock_default %}') + 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"""
+ +
%(block_content)s
+
""" % {'block_content': block_content, 'block_slug': block_slug} + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "' + \ + block_slug + '" %}' + block_content + \ + '{% end_flatblock_default %}') + + 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) + + settings.AUTOCREATE_STATIC_BLOCKS = old_setting + + def testTagDefault_DontAutoCreate(self): + block_content = 'This is the default content of block new2' + block_slug = 'block_default_new2' + expected = u"" + tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "' + \ + block_slug + '" %}' + block_content + \ + '{% end_flatblock_default %}') + + old_setting = settings.AUTOCREATE_STATIC_BLOCKS + settings.AUTOCREATE_STATIC_BLOCKS = False + + self.assertEqual(expected, tpl.render(template.Context({})).strip()) + self.assertEqual(FlatBlock.objects.filter(slug=block_slug).count(), 0) + + settings.AUTOCREATE_STATIC_BLOCKS = old_setting From ef6b5aa56f740b8fcbc150d044166752c0c8b9f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20P=C3=A9rez=20Marqu=C3=A9s?= Date: Thu, 16 Jun 2011 01:49:47 -0400 Subject: [PATCH 2/9] Revert "Added 'flatblock_default' template tag" This reverts commit a1273dd2b3b138845a2918406b10554c6556ecfd. --- flatblocks/templatetags/flatblock_tags.py | 144 ---------------------- flatblocks/tests.py | 77 ------------ 2 files changed, 221 deletions(-) diff --git a/flatblocks/templatetags/flatblock_tags.py b/flatblocks/templatetags/flatblock_tags.py index e9c4280..6b353e0 100644 --- a/flatblocks/templatetags/flatblock_tags.py +++ b/flatblocks/templatetags/flatblock_tags.py @@ -188,147 +188,3 @@ def render(self, context): register.tag('flatblock', do_get_flatblock) register.tag('plain_flatblock', do_plain_flatblock) - - -class FlatBlockDefaultWrapper(object): - def __init__(self, end_tag_name): - self.end_tag_name = end_tag_name - super(FlatBlockDefaultWrapper, self).__init__() - - def prepare(self, parser, token): - """ - The parser checks for following tag-configurations:: - - {% flatblock_default {block} %}{% end_flatblock_default %} - {% flatblock_default {block} {timeout} %}{% end_flatblock_default %} - {% flatblock_default {block} using {tpl_name} %}{% end_flatblock_default %} - {% flatblock_default {block} {timeout} using {tpl_name} %}{% end_flatblock_default %} - """ - self.inner_nodelist = parser.parse((self.end_tag_name, )) - parser.delete_first_token() - - tokens = token.split_contents() - self.is_variable = False - self.tpl_is_variable = False - self.slug = None - self.cache_time = 0 - self.tpl_name = None - tag_name, self.slug, args = tokens[0], tokens[1], tokens[2:] - num_args = len(args) - if num_args == 0: - # Only the block name was specified - pass - elif num_args == 1: - # block and timeout - self.cache_time = args[0] - pass - elif num_args == 2: - # block, "using", tpl_name - self.tpl_name = args[1] - elif num_args == 3: - # block, timeout, "using", tpl_name - self.cache_time = args[0] - self.tpl_name = args[2] - else: - raise template.TemplateSyntaxError, "%r tag should have between 1 and 4 arguments" % (tokens[0],) - # 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 - else: - self.slug = self.slug[1:-1] - # Clean up the template name - if self.tpl_name is not None: - if not(self.tpl_name[0] == self.tpl_name[-1] and self.tpl_name[0] in ('"', "'")): - self.tpl_is_variable = True - else: - self.tpl_name = self.tpl_name[1:-1] - if self.cache_time is not None and self.cache_time != 'None': - self.cache_time = int(self.cache_time) - - def __call__(self, parser, token): - self.prepare(parser, token) - return FlatBlockDefaultNode(self.slug, self.is_variable, - self.inner_nodelist, self.cache_time, - template_name=self.tpl_name, - tpl_is_variable=self.tpl_is_variable) - -class FlatBlockDefaultNode(template.Node): - def __init__(self, slug, is_variable, inner_nodelist, cache_time=0, - with_template=True, template_name=None, tpl_is_variable=False): - if template_name is None: - self.template_name = 'flatblocks/flatblock.html' - else: - if tpl_is_variable: - self.template_name = template.Variable(template_name) - else: - self.template_name = template_name - self.slug = slug - self.is_variable = is_variable - self.inner_nodelist = inner_nodelist - self.cache_time = cache_time - self.with_template = with_template - - def render(self, context): - 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 - # 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.update(context) - try: - flatblock = None - if self.cache_time != 0: - cache_key = settings.CACHE_PREFIX + real_slug - flatblock = cache.get(cache_key) - if flatblock is None: - - # 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) - else: - flatblock, _ = FlatBlock.objects.get_or_create( - slug=real_slug, - defaults = { 'content': self.inner_nodelist.render(context) }) - - 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) - else: - logger.debug("Caching %s for %s seconds" % (real_slug, - str(self.cache_time))) - cache.set(cache_key, flatblock, int(self.cache_time)) - 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 - except FlatBlock.DoesNotExist: - return '' - -class PlainFlatBlockDefaultWrapper(FlatBlockDefaultWrapper): - def __call__(self, parser, token): - self.prepare(parser, token) - return FlatBlockDefaultNode(self.slug, self.is_variable, self.inner_nodelist, self.cache_time, False) - -do_get_flatblock = FlatBlockDefaultWrapper('end_flatblock_default') -do_plain_flatblock = PlainFlatBlockDefaultWrapper('end_plain_flatblock_default') - -register.tag('flatblock_default', do_get_flatblock) -register.tag('plain_flatblock_default', do_plain_flatblock) - diff --git a/flatblocks/tests.py b/flatblocks/tests.py index 3b6510f..b12b96f 100644 --- a/flatblocks/tests.py +++ b/flatblocks/tests.py @@ -129,80 +129,3 @@ def testMissingVariableBlock(self): self.assertEqual('', tpl.render(template.Context({'name': 'foo'})).strip()) -class TagDefaultTests(TestCase): - def setUp(self): - self.testblock = FlatBlock.objects.create( - slug='block_default', - header='HEADER', - content='CONTENT_DEFAULT' - ) - - def testTagDefault(self): - expected = u"""
- -

HEADER

- -
CONTENT_DEFAULT
-
""" - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" %}This is the default content{% end_flatblock_default %}') - self.assertEqual(expected, tpl.render(template.Context({})).strip()) - - def testTagPlainDefault(self): - tpl = template.Template('{% load flatblock_tags %}{% plain_flatblock_default "block_default" %}This is the default content{% end_plain_flatblock_default %}') - self.assertEqual(u'CONTENT_DEFAULT', tpl.render(template.Context({})).strip()) - - def testUsingMissingTemplate(self): - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" using "missing_template.html" %}This is the default content{% end_flatblock_default %}') - exception = template.TemplateSyntaxError - self.assertRaises(exception, tpl.render, template.Context({})) - - def testSyntax(self): - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" %}This is the default content{% end_flatblock_default %}') - tpl.render(template.Context({})) - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" 123 %}This is the default content{% end_flatblock_default %}') - tpl.render(template.Context({})) - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" using "flatblocks/flatblock.html" %}This is the default content{% end_flatblock_default %}') - tpl.render(template.Context({})) - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "block_default" 123 using "flatblocks/flatblock.html" %}This is the default content{% end_flatblock_default %}') - tpl.render(template.Context({})) - - def testBlockAsVariable(self): - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default blockvar %}This is the default content{% end_flatblock_default %}') - 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"""
- -
%(block_content)s
-
""" % {'block_content': block_content, 'block_slug': block_slug} - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "' + \ - block_slug + '" %}' + block_content + \ - '{% end_flatblock_default %}') - - 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) - - settings.AUTOCREATE_STATIC_BLOCKS = old_setting - - def testTagDefault_DontAutoCreate(self): - block_content = 'This is the default content of block new2' - block_slug = 'block_default_new2' - expected = u"" - tpl = template.Template('{% load flatblock_tags %}{% flatblock_default "' + \ - block_slug + '" %}' + block_content + \ - '{% end_flatblock_default %}') - - old_setting = settings.AUTOCREATE_STATIC_BLOCKS - settings.AUTOCREATE_STATIC_BLOCKS = False - - self.assertEqual(expected, tpl.render(template.Context({})).strip()) - self.assertEqual(FlatBlock.objects.filter(slug=block_slug).count(), 0) - - settings.AUTOCREATE_STATIC_BLOCKS = old_setting From b233a3958db0f83e5e6311ee72b5bac0a156a81a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20P=C3=A9rez=20Marqu=C3=A9s?= Date: Thu, 16 Jun 2011 13:10:04 -0400 Subject: [PATCH 3/9] 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. --- flatblocks/settings.py | 5 + flatblocks/templatetags/flatblock_tags.py | 95 +++++++++- flatblocks/tests.py | 204 ++++++++++++++++++++++ 3 files changed, 299 insertions(+), 5 deletions(-) diff --git a/flatblocks/settings.py b/flatblocks/settings.py index 75f8a9e..8c3d828 100644 --- a/flatblocks/settings.py +++ b/flatblocks/settings.py @@ -3,3 +3,8 @@ 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) diff --git a/flatblocks/templatetags/flatblock_tags.py b/flatblocks/templatetags/flatblock_tags.py index 6b353e0..011c65d 100644 --- a/flatblocks/templatetags/flatblock_tags.py +++ b/flatblocks/templatetags/flatblock_tags.py @@ -73,6 +73,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 +100,34 @@ 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): + # 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 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,7 +146,10 @@ 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): @@ -120,7 +161,9 @@ def __call__(self, parser, token): 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,6 +176,12 @@ 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): if self.is_variable: real_slug = template.Variable(self.slug).resolve(context) @@ -142,6 +191,12 @@ def render(self, context): 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 + # 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: @@ -160,11 +215,41 @@ def render(self, context): # FLATBLOCKS_AUTOCREATE_STATIC_BLOCKS setting if self.is_variable or not settings.AUTOCREATE_STATIC_BLOCKS: flatblock = FlatBlock.objects.get(slug=real_slug) + + # 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 settings.STRICT_DEFAULT_CHECK: + if not flatblock.header and real_default_header is not None: + flatblock.header = real_default_header + flatblock_updated = True + if not flatblock.content and self.default_content: + if isinstance(self.default_content, template.NodeList): + real_default_contents = self.default_content.render(context) + else: + real_default_contents = self.default_content + flatblock.content = real_default_contents + flatblock_updated = True + + if flatblock_updated and settings.STRICT_DEFAULT_CHECK_UPDATE: + flatblock.save() else: + if isinstance(self.default_content, template.NodeList): + real_default_contents = self.default_content.render(context) + else: + real_default_contents = self.default_content + + if real_default_contents is None: + real_default_contents = real_slug + flatblock, _ = FlatBlock.objects.get_or_create( - slug=real_slug, - defaults = {'content': real_slug} - ) + slug=real_slug, + defaults = { + 'content': real_default_contents, + 'header': real_default_header, + }) + 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" diff --git a/flatblocks/tests.py b/flatblocks/tests.py index b12b96f..e57c659 100644 --- a/flatblocks/tests.py +++ b/flatblocks/tests.py @@ -129,3 +129,207 @@ def testMissingVariableBlock(self): self.assertEqual('', tpl.render(template.Context({'name': 'foo'})).strip()) +class TagDefaultTests(TestCase): + def setUp(self): + self.testblock = FlatBlock.objects.create( + slug='block_default', + header='HEADER', + content='CONTENT_DEFAULT' + ) + + def testTagDefault(self): + expected = u"""
+ +

HEADER

+ +
CONTENT_DEFAULT
+
""" + 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()) + + def testTagPlainDefault(self): + tpl = template.Template('{% load flatblock_tags %}{% plain_flatblock "block_default" with-default %}This is the default content{% end_plain_flatblock %}') + self.assertEqual(u'CONTENT_DEFAULT', tpl.render(template.Context({})).strip()) + + def testUsingMissingTemplate(self): + tpl = template.Template('{% load flatblock_tags %}{% flatblock "block_default" using "missing_template.html" with-default %}This is the default content{% end_flatblock %}') + exception = template.TemplateSyntaxError + self.assertRaises(exception, 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({})) + + 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"""
+ +
%(block_content)s
+
""" % {'block_content': block_content, 'block_slug': block_slug} + tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \ + block_slug + '" with-default %}' + 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) + + settings.AUTOCREATE_STATIC_BLOCKS = old_setting + + def testTagDefault_AutoCreateWithHeader(self): + block_header = 'Header of block new3' + block_content = 'This is the default content of block new3' + block_slug = 'block_default_new3' + expected = u"""
+ +

%(block_header)s

+ +
%(block_content)s
+
""" % {'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"""
+ +

%(block_header)s

+ +
%(block_content)s
+
""" % {'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 new2' + block_slug = 'block_default_new2' + expected = u"" + tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \ + block_slug + '" with-default %}' + block_content + \ + '{% end_flatblock %}') + + old_setting = settings.AUTOCREATE_STATIC_BLOCKS + settings.AUTOCREATE_STATIC_BLOCKS = False + + self.assertEqual(expected, tpl.render(template.Context({})).strip()) + self.assertEqual(FlatBlock.objects.filter(slug=block_slug).count(), 0) + + settings.AUTOCREATE_STATIC_BLOCKS = old_setting + + def testTagDefault_CheckStrictFieldsNoUpdate(self): + block_header = 'Header of block NEW' + block_content = 'This is the content of block new' + block_slug = 'block_default_NEW' + + flatblock = FlatBlock.objects.create(slug=block_slug) + + expected = u"""
+ +

%(block_header)s

+ +
%(block_content)s
+
""" % {'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' + block_content = 'This is the content of block new' + block_slug = 'block_default_NEW' + + flatblock = FlatBlock.objects.create(slug=block_slug) + + expected = u"""
+ +

%(block_header)s

+ +
%(block_content)s
+
""" % {'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 From 8848e6bffb4af4317e01a28825aae32566c6c9ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20P=C3=A9rez=20Marqu=C3=A9s?= Date: Tue, 16 Aug 2011 09:51:34 -0400 Subject: [PATCH 4/9] 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 --- flatblocks/settings.py | 3 + flatblocks/templatetags/flatblock_tags.py | 112 +++++++++------ flatblocks/tests.py | 167 ++++++++++++++-------- 3 files changed, 179 insertions(+), 103 deletions(-) diff --git a/flatblocks/settings.py b/flatblocks/settings.py index 8c3d828..5a141bd 100644 --- a/flatblocks/settings.py +++ b/flatblocks/settings.py @@ -1,4 +1,5 @@ from django.conf import settings +from django.core.cache import cache CACHE_PREFIX = getattr(settings, 'FLATBLOCKS_CACHE_PREFIX', 'flatblocks_') AUTOCREATE_STATIC_BLOCKS = getattr(settings, @@ -8,3 +9,5 @@ '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) diff --git a/flatblocks/templatetags/flatblock_tags.py b/flatblocks/templatetags/flatblock_tags.py index 011c65d..e857b1f 100644 --- a/flatblocks/templatetags/flatblock_tags.py +++ b/flatblocks/templatetags/flatblock_tags.py @@ -47,6 +47,7 @@ from django.core.cache import cache from flatblocks import settings +from flatblocks.models import FlatBlock import logging @@ -54,8 +55,6 @@ register = template.Library() logger = logging.getLogger(__name__) -FlatBlock = models.get_model('flatblocks', 'flatblock') - class BasicFlatBlockWrapper(object): def prepare(self, parser, token): """ @@ -101,7 +100,7 @@ def prepare(self, parser, token): else: raise template.TemplateSyntaxError, "%r tag should have between 1 and 4 arguments" % (tokens[0],) - if len(default_args): + 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 @@ -110,8 +109,13 @@ def prepare(self, parser, token): 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 \ @@ -154,7 +158,12 @@ def __call__(self, parser, token): 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() @@ -187,6 +196,7 @@ def render(self, context): 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: @@ -197,17 +207,31 @@ def render(self, 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 + + #if real_default_contents is None: + #real_default_contents = real_slug + # 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. @@ -215,46 +239,36 @@ def render(self, context): # FLATBLOCKS_AUTOCREATE_STATIC_BLOCKS setting if self.is_variable or not settings.AUTOCREATE_STATIC_BLOCKS: flatblock = FlatBlock.objects.get(slug=real_slug) - - # 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 settings.STRICT_DEFAULT_CHECK: - if not flatblock.header and real_default_header is not None: - flatblock.header = real_default_header - flatblock_updated = True - if not flatblock.content and self.default_content: - if isinstance(self.default_content, template.NodeList): - real_default_contents = self.default_content.render(context) - else: - real_default_contents = self.default_content - flatblock.content = real_default_contents - flatblock_updated = True - - if flatblock_updated and settings.STRICT_DEFAULT_CHECK_UPDATE: - flatblock.save() else: - if isinstance(self.default_content, template.NodeList): - real_default_contents = self.default_content.render(context) - else: - real_default_contents = self.default_content - - if real_default_contents is None: - real_default_contents = real_slug - - flatblock, _ = FlatBlock.objects.get_or_create( - slug=real_slug, - defaults = { - 'content': real_default_contents, - 'header': real_default_header, - }) + try: + flatblock = FlatBlock.objects.get(slug=real_slug) + except FlatBlock.DoesNotExist: + flatblock = FlatBlock.objects.create(slug=real_slug, + content=real_default_contents or real_slug, + header=real_default_header) + flatblock.save() + flatblock_created = True + + # 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))) @@ -262,14 +276,22 @@ 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) + 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) diff --git a/flatblocks/tests.py b/flatblocks/tests.py index e57c659..7d4120d 100644 --- a/flatblocks/tests.py +++ b/flatblocks/tests.py @@ -34,7 +34,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') @@ -61,11 +61,11 @@ def setUp(self): 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 = """
@@ -76,22 +76,22 @@ def testExistingTemplate(self):
""" 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({})) + 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 +100,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 +113,17 @@ def testMissingStaticBlock(self):
foo
""" 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,43 +132,62 @@ 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): - self.testblock = FlatBlock.objects.create( - slug='block_default', - header='HEADER', - content='CONTENT_DEFAULT' - ) + 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"""
-

HEADER

- -
CONTENT_DEFAULT
+
This is the default content
""" + + 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()) + 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'CONTENT_DEFAULT', tpl.render(template.Context({})).strip()) + 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 %}') - exception = template.TemplateSyntaxError - self.assertRaises(exception, tpl.render, template.Context({})) + self.assertRaises(template.TemplateSyntaxError, 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.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.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.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.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 %}') @@ -181,36 +204,34 @@ def testTagDefault_AutoCreate(self): block_slug + '" with-default %}' + block_content + \ '{% end_flatblock %}') - old_setting = settings.AUTOCREATE_STATIC_BLOCKS settings.AUTOCREATE_STATIC_BLOCKS = True - self.assertEqual(expected, tpl.render(template.Context({})).strip()) + self.assertEqual(expected, tpl.render(template.Context()).strip()) flatblock = FlatBlock.objects.get(slug=block_slug) self.assertEqual(flatblock.content, block_content) - settings.AUTOCREATE_STATIC_BLOCKS = old_setting - def testTagDefault_AutoCreateWithHeader(self): - block_header = 'Header of block new3' - block_content = 'This is the default content of block new3' - block_slug = 'block_default_new3' + block_header = 'Header of block new2' + block_content = 'This is the default content of block new2' + block_slug = 'block_default_new2' expected = u"""

%(block_header)s

%(block_content)s
-
""" % {'block_content': block_content, 'block_slug': block_slug, +""" % {'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 %}') + 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()) + self.assertEqual(expected, tpl.render(template.Context()).strip()) flatblock = FlatBlock.objects.get(slug=block_slug) self.assertEqual(flatblock.content, block_content) @@ -247,25 +268,55 @@ def testTagDefault_AutoCreateWithHeaderAsVar(self): settings.AUTOCREATE_STATIC_BLOCKS = old_setting def testTagDefault_DontAutoCreate(self): - block_content = 'This is the default content of block new2' - block_slug = 'block_default_new2' - expected = u"" + block_content = 'This is the default content of block new4' + block_slug = 'block_default_new4' + + expected = u'
' + \ + '\n\n
' + block_content + \ + '
\n
' + tpl = template.Template('{% load flatblock_tags %}{% flatblock "' + \ block_slug + '" with-default %}' + block_content + \ '{% end_flatblock %}') - old_setting = settings.AUTOCREATE_STATIC_BLOCKS settings.AUTOCREATE_STATIC_BLOCKS = False - self.assertEqual(expected, tpl.render(template.Context({})).strip()) + self.assertEqual(expected, tpl.render(template.Context()).strip()) self.assertEqual(FlatBlock.objects.filter(slug=block_slug).count(), 0) - settings.AUTOCREATE_STATIC_BLOCKS = old_setting + 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' + ) + + block_content = 'This is the new content of "block_existing"' + block_header = 'This is the new header of "block_existing"' + + expected = u'
\n\n ' + \ + '

HEADER_OF_SAVED_BLOCK

\n\n ' + \ + '
CONTENT_OF_SAVED_BLOCK
\n
' + + 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' - block_content = 'This is the content of block new' - block_slug = 'block_default_NEW' + 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) @@ -288,7 +339,7 @@ def testTagDefault_CheckStrictFieldsNoUpdate(self): settings.STRICT_DEFAULT_CHECK_UPDATE = False settings.AUTOCREATE_STATIC_BLOCKS = False - self.assertEqual(expected, tpl.render(template.Context({})).strip()) + self.assertEqual(expected, tpl.render(template.Context()).strip()) flatblock = FlatBlock.objects.get(slug=block_slug) self.assertEqual(flatblock.content, None) @@ -299,9 +350,9 @@ def testTagDefault_CheckStrictFieldsNoUpdate(self): settings.STRICT_DEFAULT_CHECK_UPDATE = old_setting_strictcheckupdate def testTagDefault_CheckStrictFieldsDoUpdate(self): - block_header = 'Header of block NEW' - block_content = 'This is the content of block new' - block_slug = 'block_default_NEW' + 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) @@ -324,7 +375,7 @@ def testTagDefault_CheckStrictFieldsDoUpdate(self): settings.STRICT_DEFAULT_CHECK_UPDATE = True settings.AUTOCREATE_STATIC_BLOCKS = False - self.assertEqual(expected, tpl.render(template.Context({})).strip()) + self.assertEqual(expected, tpl.render(template.Context()).strip()) flatblock = FlatBlock.objects.get(slug=block_slug) self.assertEqual(flatblock.content, block_content) From 06b43255821ffdc6215744b83631196414d2c859 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20P=C3=A9rez=20Marqu=C3=A9s?= Date: Wed, 17 Aug 2011 02:50:40 -0400 Subject: [PATCH 5/9] Removed comment --- flatblocks/templatetags/flatblock_tags.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/flatblocks/templatetags/flatblock_tags.py b/flatblocks/templatetags/flatblock_tags.py index e857b1f..a4dc3c8 100644 --- a/flatblocks/templatetags/flatblock_tags.py +++ b/flatblocks/templatetags/flatblock_tags.py @@ -213,9 +213,6 @@ def render(self, context): else: real_default_contents = self.default_content - #if real_default_contents is None: - #real_default_contents = real_slug - # 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: From 0fe5b0150d0f27ab6a1559db3b38dddbe688350b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20P=C3=A9rez=20Marqu=C3=A9s?= Date: Fri, 19 Aug 2011 16:55:03 -0400 Subject: [PATCH 6/9] Fixed DebugNodeList reference --- flatblocks/locale/de/LC_MESSAGES/django.mo | Bin 958 -> 831 bytes flatblocks/locale/no/LC_MESSAGES/django.mo | Bin 907 -> 844 bytes flatblocks/locale/ru/LC_MESSAGES/django.mo | Bin 1129 -> 1066 bytes flatblocks/templatetags/flatblock_tags.py | 3 ++- 4 files changed, 2 insertions(+), 1 deletion(-) diff --git a/flatblocks/locale/de/LC_MESSAGES/django.mo b/flatblocks/locale/de/LC_MESSAGES/django.mo index d45ed530551e3605f06f019086cef232bde41ca4..ffe488c39739f6b8d20225b98ce438ec7e6b921c 100644 GIT binary patch delta 237 zcmYk#tqKA`6o%omXLZM44DKClTQCTM(WF6}f6XG8y#%j7Q05*CB3Mm&83v0Y*en*S z??HnHKAwR&^UcwnqE);oi^z`HTuGhWNJ6TCh{Glpu!TkJVuWMN-~>~g;u)9N$C--M z@PM}ez&t+D`rax%DRI#7TU0?SijfY<5qn^d|HnS1Ls*mS@50G?yZ5hP;OE*1N5hWa LXyV(N`nz5}HBlKW delta 366 zcmZ{e!AiqG6h$YAw3xaSi>?N{vNB;3ip5#kHbElRlq3{f#&#@`(v&1ExGHW1Magd{ z{(=68s0%;D8{D{Y;Bej>E_ddw@>+e^T#-NL39|{FK?8h(D$o={bhrlB;4QcU@4{>F z9^8Zt_!gW4AN#jT2!q?&Z(hRd*r#yWx70|TY+$&-MOkzYmqms4`0=tDq{)>W<;)$k zp-i(lnF%`Zy%VPw(xKxAu6L&Ua-O6)>t~aA%({z7#==BUr{8f;k2<#PJ3*iiypZ)$ z8RckTc9cs&EpD2Ox0uzYmL)jf=N9J(GG8v^@+IVU{tp&+N>B*3S$ruiZINFVb+xg5 ZEN3!BJN|JkXg9i$Q_77)~fHN)7-3 diff --git a/flatblocks/locale/no/LC_MESSAGES/django.mo b/flatblocks/locale/no/LC_MESSAGES/django.mo index dea453946c0adc3aa085938218e0ede4c8cb3096..5b9e42849d2f547cc85177209e0f2edfb73676fc 100644 GIT binary patch delta 88 zcmeBXKf^X5#g&8Pu<_6L%%nS@%Kw1Du avjAynAgv9g6(+8HI(ZkP#^$e#(-;92R1H-C delta 151 zcmX@Z*3CX4#np+CfuR?O^%xi!E-*1L7y{}4K$;y$8!|I6Z~|#dAk7V=oq;qLkoE`C zEI>L6NNWS>_=zi@Y8T~ar6!l?dZy@xr4|)u=I2={a0R6nC_&^9t9&H&O3EE88f(Jso*N=+`&^-R$XOD!tS%+Iq@;0j7D$S*3<^({`%Own~JO)u6B i$p;Eg?q$>z3h>trN-fI-snm5zEJ?Le*u0golnDT=i6heh diff --git a/flatblocks/templatetags/flatblock_tags.py b/flatblocks/templatetags/flatblock_tags.py index a4dc3c8..0d75bcf 100644 --- a/flatblocks/templatetags/flatblock_tags.py +++ b/flatblocks/templatetags/flatblock_tags.py @@ -43,6 +43,7 @@ from django import template from django.template import loader +from django.template import debug as template_debug from django.db import models from django.core.cache import cache @@ -208,7 +209,7 @@ def render(self, context): real_default_header = self.default_header if isinstance(self.default_content, - (template.NodeList, template.debug.DebugNodeList)): + (template.NodeList, template_debug.DebugNodeList)): real_default_contents = self.default_content.render(context) else: real_default_contents = self.default_content From 0d7d47a81a15d01f1f92013bdc39c44cb6592995 Mon Sep 17 00:00:00 2001 From: Mandx Date: Wed, 18 Apr 2012 20:37:01 -0400 Subject: [PATCH 7/9] Space removal --- flatblocks/models.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flatblocks/models.py b/flatblocks/models.py index 2780cb4..22ce558 100644 --- a/flatblocks/models.py +++ b/flatblocks/models.py @@ -11,7 +11,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, unique=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, @@ -21,7 +21,7 @@ class FlatBlock(models.Model): def __unicode__(self): return u"%s" % (self.slug,) - + def save(self, *args, **kwargs): super(FlatBlock, self).save(*args, **kwargs) # Now also invalidate the cache used in the templatetag From cf852aec66a7e8b60c137c5fe242844420339b1e Mon Sep 17 00:00:00 2001 From: Mandx Date: Thu, 19 Apr 2012 21:44:32 -0400 Subject: [PATCH 8/9] Set my name --- setup.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/setup.py b/setup.py index 6f23e19..e9a558e 100644 --- a/setup.py +++ b/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', From 71a52406e64fb01c09a7b0804dcf806f99f34a27 Mon Sep 17 00:00:00 2001 From: Mandx Date: Thu, 19 Apr 2012 21:47:46 -0400 Subject: [PATCH 9/9] Added support for site-dependent flatblocks --- flatblocks/admin.py | 5 +- ..._del_unique_flatblock_slug__add_unique_.py | 55 +++++++++++++++++++ flatblocks/models.py | 15 +++-- flatblocks/templatetags/flatblock_tags.py | 42 +++++++++----- flatblocks/tests.py | 22 +++++--- test_project/settings.py | 15 ++++- 6 files changed, 125 insertions(+), 29 deletions(-) create mode 100644 flatblocks/migrations/0002_auto__add_field_flatblock_site__del_unique_flatblock_slug__add_unique_.py diff --git a/flatblocks/admin.py b/flatblocks/admin.py index d54e68b..ae048c2 100644 --- a/flatblocks/admin.py +++ b/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) diff --git a/flatblocks/migrations/0002_auto__add_field_flatblock_site__del_unique_flatblock_slug__add_unique_.py b/flatblocks/migrations/0002_auto__add_field_flatblock_site__del_unique_flatblock_slug__add_unique_.py new file mode 100644 index 0000000..8c2195b --- /dev/null +++ b/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'] \ No newline at end of file diff --git a/flatblocks/models.py b/flatblocks/models.py index a749308..c351df3 100644 --- a/flatblocks/models.py +++ b/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') diff --git a/flatblocks/templatetags/flatblock_tags.py b/flatblocks/templatetags/flatblock_tags.py index 0d75bcf..83e468b 100644 --- a/flatblocks/templatetags/flatblock_tags.py +++ b/flatblocks/templatetags/flatblock_tags.py @@ -42,10 +42,11 @@ """ from django import template +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 django.db import models -from django.core.cache import cache from flatblocks import settings from flatblocks.models import FlatBlock @@ -56,6 +57,7 @@ register = template.Library() logger = logging.getLogger(__name__) + class BasicFlatBlockWrapper(object): def prepare(self, parser, token): """ @@ -193,6 +195,7 @@ def __init__(self, slug, is_variable, cache_time=0, with_template=True, 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: @@ -236,16 +239,25 @@ def render(self, context): # 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: - try: - flatblock = FlatBlock.objects.get(slug=real_slug) - except FlatBlock.DoesNotExist: - flatblock = FlatBlock.objects.create(slug=real_slug, - content=real_default_contents or real_slug, - header=real_default_header) - flatblock.save() - flatblock_created = True + # 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 @@ -277,8 +289,12 @@ def render(self, context): 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) + 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 '' diff --git a/flatblocks/tests.py b/flatblocks/tests.py index 7d4120d..4118c11 100644 --- a/flatblocks/tests.py +++ b/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') @@ -55,7 +57,8 @@ def setUp(self): self.testblock = FlatBlock.objects.create( slug='block', header='HEADER', - content='CONTENT' + content='CONTENT', + site=Site.objects.get_current(), ) def testLoadingTaglib(self): @@ -80,7 +83,7 @@ def testExistingTemplate(self): def testUsingMissingTemplate(self): tpl = template.Template('{% load flatblock_tags %}{% flatblock "block" using "missing_template.html" %}') - exception = template.TemplateSyntaxError + exception = template.TemplateDoesNotExist self.assertRaises(exception, tpl.render, template.Context()) def testSyntax(self): @@ -165,7 +168,7 @@ def testTagPlainDefault(self): 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.TemplateSyntaxError, tpl.render, template.Context()) + 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 %}') @@ -290,7 +293,8 @@ def testTagDefault_TestExistingAutoCreate(self): testblock = FlatBlock.objects.create( slug=block_slug, header='HEADER_OF_SAVED_BLOCK', - content='CONTENT_OF_SAVED_BLOCK' + content='CONTENT_OF_SAVED_BLOCK', + site=Site.objects.get_current(), ) block_content = 'This is the new content of "block_existing"' @@ -318,7 +322,8 @@ def testTagDefault_CheckStrictFieldsNoUpdate(self): block_content = 'This is the content of block new 5' block_slug = 'block_default_NEW5' - flatblock = FlatBlock.objects.create(slug=block_slug) + flatblock = FlatBlock.objects.create( + slug=block_slug, site=Site.objects.get_current()) expected = u"""
@@ -354,7 +359,10 @@ def testTagDefault_CheckStrictFieldsDoUpdate(self): block_content = 'This is the content of block new 6' block_slug = 'block_default_NEW6' - flatblock = FlatBlock.objects.create(slug=block_slug) + flatblock = FlatBlock.objects.create( + slug=block_slug, + site=Site.objects.get_current() + ) expected = u"""
diff --git a/test_project/settings.py b/test_project/settings.py index b0ffa33..cd77b85 100644 --- a/test_project/settings.py +++ b/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' )