【发布时间】:2019-04-20 17:07:53
【问题描述】:
我正在尝试在使用 Django CMS 构建的网站上设置标题的可编辑背景图像。
尝试了来自 Using django-cms, how can I allow the user to specify a background image 的指令,但在生成的 HTML 代码中仍然出现“background-image: url('')”。
这是我添加的代码以尝试添加背景图像:
- 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.filerimage.image}
#return {'cover': cover_image_plugin.get_plugin_instance()[0]}
return {}
- settings.py 结束:
TEMPLATES[0]['OPTIONS']['context_processors'].append('context_processors.cover_image')
- base.html:
...
{% placeholder "cover_image" %}
<header class="masthead" style="background-image: url('{{ cover.url|urlencode }}')">
...
谁能帮我修复它并使背景图像正常工作?
【问题讨论】:
-
如果您在模板中使用
{{ cover }}会打印任何内容吗? -
@AmanGarg,不,什么都没有
-
那么问题出在您的
context_processors.py中。您应该调试每一行并检查您的cover_image()是否返回某些内容。 -
这并不是真正应该如何使用插件的方式。如果你有一个插件,你会像你一样将
placeholder添加到模板中,但是插件自己的模板和render会将cover传递给上下文并包含标记。根据您所包含的内容,您可能应该将其作为页面扩展来执行。您可以通过扩展页面模型为每个页面提供图像; docs.django-cms.org/en/latest/how_to/extending_page_title.html -
@markwalker_,感谢您的帮助。尝试使用您引用的手册。几乎一切正常。我创建了带有页面扩展名的应用程序,唯一不好的是路径有问题。在模板中我使用“{% static request.current_page.coverimageextension.image.url %}”,在生成的 HTML 中我得到“/static/media/cover_images/Controversial-mountain-names-featimg_mod.jpg”,但图像在另一个路径 - “/data/media/cover_images/Controversial-mountain-names-featimg_mod.jpg”。在 models.py 中,我使用“image = models.ImageField(upload_to='cover_images')”。你能帮我解决路径吗?
标签: python django django-cms