I am creating a django-cms site for a client. I would like to do something like:
You are on the right track, once that's there when all you need is the plugin which in this case you can use filer. And to make it better you can use the CMS_PLACEHOLDER_CONF setting to only allow that one plugin to be placeholder inside the background-image placeholder, like so:
CMS_PLACEHOLDER_CONF = {
'background-image': {
"plugins": ('YourImagePlugin', ),
'name':"Background Image",
'limits': {
'global': 1,
},
},
}
Great answer Flimm, thanks!
I get an error, however, in the context processor saying that a CMSPlugin
object does not have a filerimage
attribute. Here's the context processor that works for me:
# in context_processors.py
from cms.models.pluginmodel import CMSPlugin
def cover_image(request):
page = request.current_page
if page:
cover_image_plugin = CMSPlugin.objects.filter(
placeholder__page=page,
placeholder__slot='cover_image',
plugin_type='FilerImagePlugin',
).first()
if cover_image_plugin:
return {'cover': cover_image_plugin.get_plugin_instance()[0]}
return {}
Note the change in the but last line. get_plugin_instance
retrieves the rightly subclassed instance object as the first entry of a tuple. (I use Django CMS 3.4)
As a last remark, the cover_image
placeholder needs to be in a place that is not rendered.
Paulo is right, the first step is to configure a placeholder so that it can only take at most one image plugin, in this case, FileImagePlugin
. Do that by modifying CMS_PLACEHOLDER_CONF:
CMS_PLACEHOLDER_CONF = {
'cover_image': {
'plugins': ['FilerImagePlugin'],
'name': _('Cover Image'),
'limits': {'global': 1},
},
}
Make sure in your template, you are showing this placeholder somewhere:
{% load cms_tags %}
{% placeholder "cover_image" %}
This will render the image in an <img>
tag. But what if you want just the URL of the image? That's what the second step is.
Create a context processor that will give you the image directly. The details will modify depending on what image plugin you're using, but this is the one I used:
# in context_processors.py
from cms.models.pluginmodel import CMSPlugin
def page_extra(request):
page = request.current_page
if page:
cover_image_plugin = CMSPlugin.objects.filter(
placeholder__page=page,
placeholder__slot='cover_image',
plugin_type='FilerImagePlugin',
).first()
if cover_image_plugin:
return {'cover': cover_image_plugin.filerimage.image}
return {}
Remember to install the context processor in your settings.py
file:
TEMPLATES[0]['OPTIONS']['context_processors'].append('example.context_processors.page_extra')
Now in your template, you can access the URL using cover.url
, like this:
<body
{% if cover %}
style="background-image: url('{{ cover.url|urlencode }}')"
{% endif %}
>