简体   繁体   English

在 .py 文件中引用 django 中的静态文件(不在模板中)

[英]Reference static files in django in .py files ( NOT in templates)

I've been like an hour searching how to reference static files in django, but I only found how to do it in templates.我已经花了一个小时搜索如何在 django 中引用静态文件,但我只找到了如何在模板中做到这一点。 In my project, I succeeded in referencing static files in my templates, but I DON'T want to do it in templates, I want to do it in my .py files.在我的项目中,我成功地在我的模板中引用了静态文件,但我不想在模板中这样做,我想在我的 .py 文件中这样做。

I think that i have to import static from somewere, I've tried with this:我想我必须从某个地方导入静态,我试过这个:

from django.templatetags.static import static
from django.conf.urls.static import static

And trying to reference it like this并试图像这样引用它

'<a href=/url> <img  src="{{ STATIC_URL }}image.png" ></a>'

I've tried all possible combinations like我已经尝试了所有可能的组合,比如

{% static image.png %}
{{static image.png}}

and so on...等等...

Thanks!谢谢!

from django.templatetags.static import static
'<a href=/url> <img  src="{0}" ></a>'.format(static("image.png"))

Note that django.templatetags.static is actually a function.注意django.templatetags.static实际上是一个函数。 The template engine calls that function when you use the template tag.当您使用模板标签时,模板引擎会调用该函数。

If you want to find the actual file on disk, you can use the finders class of the staticfiles app:如果你想找到磁盘上的实际文件,你可以使用发现者staticfiles应用程序:

>>> from django.contrib.staticfiles import finders
>>> finders.find("icons/exclamation.svg")
'C:\\<project folder>\\<project name>\\<app name>\\static\\icons\\exclamation.svg'

Django Docs Django 文档

You can read django configuration to get STATIC_URL which contains URL base part for static files:您可以阅读 django 配置以获取包含静态文件的 URL 基础部分的STATIC_URL

from django.conf import settings
import urlparse

print '<a href=/url> <img src="%s"></a>' % urlparse.urljoin(settings.STATIC_URL, 'image.png')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM