Using django-cms, how can I allow the user to specify a background image

前端 未结 3 1617
无人及你
无人及你 2021-01-13 05:34

I am creating a django-cms site for a client. I would like to do something like:



        
3条回答
  •  时光取名叫无心
    2021-01-13 06:04

    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 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:

    
    

提交回复
热议问题