Django-CMS and Custom Template Tags
I'm working with a Django application and we are using Django CMS. The users are able to add HTML through Django's admin. I wanted to version our images, as we are developing locally, then deploying to a test server so that the client can see and accept all the work we have done, and finally we have a production environment. We wanted all of these three environments to have versioned static images, so that when we are developing locally, the static files are server from own machine. The test and live environments also needed to have their own versionings.
This was what I wanted to have: Local: <img src="/static/imgs/img.jpg"> Test: <img src="https://s3-eu-west-1.amazonaws.com/test-bucket/static/imgs/img.jpg"> Production: <img src="https://s3-eu-west-1.amazonaws.com/production-bucket/static/imgs/img.jpg">
As I mentioned above, we are using Django CMS, and the urls were being hardcoded directly there. To achieve the desired behaviour I decided to create a custom template tag, and have Django re-render the CMS pages.
I created a super-simple context processor and added that into TEMPLATE_CONTEXT_PROCESSORS:
def cms_tag(request): return {"cms_images": settings.STATIC_URL} TEMPLATE_CONTEXT_PROCESSORS += ("path.to.cms_tag",)
Next, I created the following function:
import traceback from django.template import Template def render_django_cms_templates(isntance, placeholder, rendered_content, original_context): try: t = Template(rendered_content) rendered_content = t.render(original_context) except: import traceback rendered_content = "<p> {} </p>".format(traceback.format_exc()) return rendered_content CMS_PLUGIN_PROCESSORS = ('path.to.render_django_cms_templates',)
Now we can write the urls in the following way, and the path is correct in all of the three environments: <img src="{{cms_images}}imgs/img.jpg">
Cheers!
















