django 无法通过css从模型中加载图像background-image在我的html页面

rqcrx0a6  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(121)

无法加载图像从模型通过css背景图像在我的html页面,我想加载图像从模型,我上传到我的html页面通过background-image in css
我的型号:

class Home_options(models.Model):
    background_img = models.ImageField(upload_to='images/',null=True, blank=True)
    your_small_img = models.ImageField(upload_to='images/',null=True, blank=True)

    # Background img
    def get_background_img(self):
        if self.background_img and hasattr(self.background_img, 'url'):
            return self.background_img.url
        else:
            return '/path/to/default/image'
        
    # your_small_img
    def get_your_small_img(self):
        if self.your_small_img and hasattr(self.your_small_img, 'url'):
            return self.your_small_img.url
        else:
            return '/path/to/default/image'`

我的css:

.header {
  background-image: -webkit-linear-gradient(bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('{{ home_options.get_background_img.url }}');
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('{{ home_options.get_background_img.url }}');
}`

我尝试使用home_options.get_background_img.urlhome_options.your_small_img.url,但它们不工作

zte4gxcn

zte4gxcn1#

获取图像在html文件不是在css|首先你必须将模型传递给视图,然后在html中使用for来使用它,代码是:

<header class="header" style="background-image: -webkit-linear-gradient(bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('{{ link.background_img.url }}')">

相关问题