首页 > 解决方案 > 无法解析剩余部分:来自 'url_for('static', filename='main.png')' 的 '('static', filename='main.png')'

问题描述

我是django初学者,我正在尝试渲染html页面。我已经有一个测试 html 页面和 URL 来测试它。

在点击 URL 时,遇到以下错误:

Could not parse the remainder: '('static', filename='main.png')' from 'url_for('static', filename='main.png')'

完整的跟踪:

Request Method:
GET
Request URL:
http://127.0.0.1:8000/xxxxx
Django Version:    3.0.2
Exception Type:    TemplateSyntaxError
Exception Value:    Could not parse the remainder: '('static', filename='main.png')' from 'url_for('static', filename='main.png')'
Exception Location:    F:\Anaconda\lib\site-packages\django\template\base.py in __init__, line 662
Python Executable:    F:\Anaconda\python.exe
Python Version:    3.7.0

我尝试过使用单引号和双引号,但它仍然不起作用。有点卡在这一点上。

任何评论/建议/提示/链接到指南表示赞赏。

标签: pythonhtmldjango

解决方案


看看这个。您必须确保在模板中加载静态,{% load static %}然后您可以让 django 通过使用生成模板中文件的链接{% static "static/path.ext" %}

因此,您将文件更改为:

.bg-image {
    background-image: url("{% static "main.png" %}");
    filter: blur(8px);
    -webkit-filter: blur(8px);
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

只要记住放在{% load static %}文件的顶部。


推荐阅读