I am doing the django tutorial on realpython https://realpython.com/get-started-with-django-1/
In one of the templates they add {% load static %} to load the static files for an app. In the same template they also load an image like this <img class="card-img-top" src="{% static project.image %}">. The static keyword here tells django to look for the filename defined in project.image in the static folder. When i remove {% load static %} the image is still displayed. So why would …
当我使用{% load static %}然后将这样的图像添加到模板中时:
<img src="{% static 'logo.png' %}">
Run Code Online (Sandbox Code Playgroud)
仅当图像存储在static同一应用程序中的方向上时,我才会获得图像。但是我要在整个项目中使用徽标,并且也要在整个项目的模板中使用徽标。当图像static以内部项目文件夹中的方向存储时,该功能不起作用。
如何在整个项目中使用静态文件?以及如何从模板访问它们?(我是一个业余开发人员,所以不在生产中;-)我的设置几乎与创建项目时的设置相同。(我只添加了一些其他的模板方向。)
谢谢您阅读此篇
我有以下项目结构:
myproject
- myapp
- manage.py
- myproject
- settings.py
- urls.py
...
- static
- templates
Run Code Online (Sandbox Code Playgroud)
我想从这个静态文件夹中提供所有静态文件。在我的settings.py中,我有以下内容:
myproject
- myapp
- manage.py
- myproject
- settings.py
- urls.py
...
- static
- templates
Run Code Online (Sandbox Code Playgroud)
但是,在我的模板之一中,当我使用以下命令调用静态文件时......
{% load static %}
...
<link href="{% static 'css/styles.css' %}" rel="stylesheet" />
Run Code Online (Sandbox Code Playgroud)
...没有加载任何内容。
但是,如果我在 myapp/static/css/styles.css 中添加 css 文件,则一切正常。如何从项目根文件夹提供静态文件?谢谢你的帮助。
python django django-templates django-static django-staticfiles
我有点难过.在开发中,我正在尝试为DJango 1.3中的应用程序提供静态和动态文件.我喜欢新的静态功能,但我似乎无法使其正常工作.
当我阅读文档时,看起来以下内容应该可行.它提供动态的东西很好,但不是静态的.
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/dynamic/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Run Code Online (Sandbox Code Playgroud) 当我使用MEDIA_URL或STATIC_URL指向/ static /当前将MEDIA_URL设置为/ static /并在CSS文件的路径中使用它时,如:
<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}css/css.css" />
Run Code Online (Sandbox Code Playgroud)
它指向/static/css.css,但尝试http://localhost/static/css.css给出404错误.
我有设置:
.....
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT …Run Code Online (Sandbox Code Playgroud)