I would like to write a filter which replaces some $variables$ in my streamfield text. What is the best way to do this in my "Page" model? I tried the following but it is sometimes not working if I save my model as draft and publish it afterwards. Does anyone know a better way doing this?
class CityPage(Page, CityVariables):
cityobject = models.ForeignKey(CityTranslated, on_delete=models.SET_NULL, null=True, blank=True)
streamfield = StreamField(BasicStreamBlock, null=True, blank=True)
content_panels = Page.content_panels + [
FieldPanel('cityobject', classname="full"),
StreamFieldPanel('streamfield'),
]
def get_streamfield(self):
for block in self.streamfield:
if type(block.value) == unicode:
block.value = self.replace_veriables(block.value)
elif type(block.value) == RichText:
block.value.source = self.replace_veriables(block.value.source)
else:
print "notimplemented"
return self.streamfield
And this is just the class which replaces $variables$ with values from my database.
class CityVariables():
def replace_veriables(self, repstr):
reprules = self.get_city_context()
for key, value in reprules.iteritems():
repstr = repstr.replace(key, value)
return repstr
def get_city_context(self):
context = {}
if self.cityobject.population:
context['$population$'] = unicode(self.cityobject.population)
if self.cityobject.transregion:
context['$region$'] = unicode(self.cityobject.transregion)
return context
class BasicStreamBlock(blocks.StreamBlock):
h2 = blocks.CharBlock(icon="title", classname="title")
h3 = blocks.CharBlock(icon="title", classname="title")
h4 = blocks.CharBlock(icon="title", classname="title")
h5 = blocks.CharBlock(icon="title", classname="title")
paragraph = blocks.RichTextBlock(icon="pilcrow")
image = ImageChooserBlock(label="Image", icon="image")
aligned_html = blocks.RawHTMLBlock(icon="code", label='Raw HTML')