Python Django静态文件处理错误
我在django中处理静态文件时出错。每当我加载网页时,图像都不会加载 html文件Python Django静态文件处理错误,python,django,static,Python,Django,Static,我在django中处理静态文件时出错。每当我加载网页时,图像都不会加载 html文件 {%for i in all_memes%} <div class="memes"> {%load static%} <a href="{%url 'meme_detail' i.id%}"><img style="width:150px;height:150px;" src="{%static '/photos/static/upload
{%for i in all_memes%}
<div class="memes">
{%load static%}
<a href="{%url 'meme_detail' i.id%}"><img style="width:150px;height:150px;" src="{%static '/photos/static/uploaded_files/{{i.photo_link}}' %}" /></a>
</div>
{%endfor%}
设置.py
STATIC_URL = '/static/'
MEDIA_ROOT=os.path.join(BASE_DIR,'photos/static')
STATIC_ROOT="/photos/static/uploaded_files"
我的应用程序的树结构看起来像->
photos
├── admin.py
├── admin.pyc
├── apps.py
├── apps.pyc
├── forms.py
├── forms.pyc
├── __init__.py
├── __init__.pyc
├── models.py
├── models.pyc
├── static
│ └── uploaded_files
│ ├── 1489928056_6771295_Screenshot_from_2017-03-19_17-58-27.png
│ └── 1489928993_8345437_Screenshot_from_2017-03-19_17-58-27.png
├── templates
│ └── photos
│ ├── add.html
│ ├── detail.html
│ ├── index.html
│ ├── invalid.html
│ ├── login.html
│ └── meme.html
├── tests.py
├── urls.py
├── urls.pyc
├── views.py
└── views.pyc
您应该在
静态
块中给出相对路径
{% static 'img_relative_path' %}
{% static i.photo_link %}
基本上,由于您已经为静态文件声明了根文件夹,因此需要给出与此路径相关的路径
e、 g
另外,您不需要在
{%static…%}
块中使用{{i.photo_link}}
,因为您可以直接使用i.photo_link
,即{%static i.photo_link%}
在html文件中使用此标记{%load staticfiles%}
您的代码应该如下所示:-
{%for i in all_memes%}
<div class="memes">
{%load static%}
<a href="{%url 'meme_detail' i.id%}"><img style="width:150px;height:150px;" src="{%static '/photos/static/uploaded_files/{{i.photo_link}}' %}" /></a>
</div>
{%endfor%}
{%for i in all_memes%}
{%load static%}
{%endfor%}
你的意思是什么。我是一个noob在这里更新了我的答案,请检查。嘿,我做了你的答案告诉我做的,现在我有一个AttributeError在/photos/memes-“FieldFile”对象没有属性“replace”,那么这是一个不同的问题本身,我想。但最有可能的情况是,检查错误说明,您必须在FieldFile
对象上执行str.replace
,而不是它的一个属性。谢谢PS。您没有{%load staticfiles%}在您的代码中,虽然这将在您当前的系统上工作,但一旦静态文件的父目录结构或路径发生更改,它将在任何其他系统上失败!!您不应该在静态块中使用完整路径!您之所以在settings.py
中保持STATIC\u ROOT
可配置,以便您可以根据环境进行更改,否则您必须更改所有模板。此外,您应该使用STATIC\u ROOT=os.path.join(BASE\u DIR,/photos/STATIC/uploaded\u files'),不要硬编码您的路径目录,使用相对路径
Complete path - /photos/static/images/random.jpg
Static root - /photos/static
Relative path - images/random.jpg
{%for i in all_memes%}
<div class="memes">
{%load static%}
<a href="{%url 'meme_detail' i.id%}"><img style="width:150px;height:150px;" src="{%static '/photos/static/uploaded_files/{{i.photo_link}}' %}" /></a>
</div>
{%endfor%}