【问题标题】:How to add background image in django-cms?如何在 django-cms 中添加背景图片?
【发布时间】: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('')”。

这是我添加的代码以尝试添加背景图像:

  1. 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 {}
  1. settings.py 结束:
TEMPLATES[0]['OPTIONS']['context_processors'].append('context_processors.cover_image')
  1. 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


【解决方案1】:

在您的项目中,添加到您的models.py

from cms.models import CMSPlugin
from filer.fields.image import FilerImageField

class MyCoverModel(CMSPlugin):
    cover = FilerImageField(
        null=True,
        blank=True,
        related_name='header_logo',
    )

cms_plugins.py 添加:

from cms.plugin_base.CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import MyCoverModel

class CoverPlugin(CMSPluginBase):
    name = "Cover"
    model = MyCoverModel
    render_template = 'my_cover.html'

plugin_pool.register_plugin(CoverPlugin)

并在templates/my_cover.html 中添加:

{% load thumbnail %}

{% thumbnail instance.cover 1000x500 crop upscale as thumb %}
<header class="masthead" style="background-image: url('{{ thumb.url }}'); width={{ thumb.width }}; height={{ thumb.height }};"></header>

注意应用程序easy-thumbnails 中模板标签缩略图的使用。在这里它将图像的大小限制为 1000 x 500 像素。

这会为您的 CMS 安装添加一个简单的插件。通过编辑占位符字段,它提供了一个名为Cover 的插件。从那里选择一个图像,它将被渲染为标题的背景。

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    相关资源
    最近更新 更多