简体   繁体   English

"Django:静态图像不会加载"

[英]Django: Static Image won't load

I have been following the official documentation to the letter, trying some of the advice for related questions on here, and just searching the web in general and I am still having no luck getting one little image to load.我一直在关注官方文档,在此处尝试有关相关问题的一些建议,并且只是在一般情况下搜索网络,但我仍然没有运气加载一张小图片。

I have an image called 'logo.png' and my project hierarchy looks like this:我有一个名为“logo.png”的图像,我的项目层次结构如下所示:

project/
   mysite/
      app/
         __init__.py
         admin.py
         models.py
         urls.py
         view.py
      mysite/
         __init__.py
         settings.py
         urls.py
         views.py
         wsgi.py
      static/
         logo.png
      templates/
         index.html
         calling_image.html

Inside settings.py I have STATIC_URL = '/static/'settings.py我有STATIC_URL = '/static/'

Inside calling_image.html I have <img src="/static/logo.png">calling_image.html我有<img src="/static/logo.png">

My template calling_image.html is called by project/mysite/app/views.py which is of course then called on by project/mysite/app/urls.py and I even tried including the following two lines (as I saw suggested a few times) at the end of my urls.py :我的模板calling_image.htmlproject/mysite/app/views.py调用,当然它随后由project/mysite/app/urls.py调用,我什至尝试包括以下两行(正如我所看到的那样)次)在我的urls.py末尾:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

Nothing works, so what have I done wrong?没有任何效果,所以我做错了什么?

Edit : Sorry I made a type, I have STATIC_URL = '/static/' with the closing slash in my settings.py and for clarification, I am running this on my dev build with python manage.py runserver编辑:对不起,我做了一个类型,我的STATIC_URL = '/static/'在我的settings.py中带有右斜杠,为了澄清起见,我正在使用python manage.py runserver在我的开发版本上运行它

Solved : So I ended up solving this myself.已解决:所以我最终自己解决了这个问题。 I created a directory resources within project/mysite/ and placed logo.png in there.我在project/mysite/中创建了一个目录resources ,并将logo.png放在那里。 I then set STATICFILES_DIRS = (os.path.join(BASE_DIR, "resources"),) and ran collecstatic and everything worked!然后我设置STATICFILES_DIRS = (os.path.join(BASE_DIR, "resources"),)并运行collecstatic并且一切正常! Didn't need to use urlpatterns += staticfiles_urlpatterns() and whatnot.不需要使用urlpatterns += staticfiles_urlpatterns()的。

It looks like you probably need the variable STATICFILES_DIRS defined in your settings.py and that should include the location of that static directory holding logo.png . 看起来你可能需要在STATICFILES_DIRS定义的变量STATICFILES_DIRS ,它应该包含该static目录持有logo.png的位置。

Django only looks for static files inside a static directory inside each app by default. Django默认只在每个应用程序内的static目录中查找静态文件。 If you have a static file outside of any app, it won't be picked up by collectstatic automatically. 如果您在任何应用程序之外有静态文件,则collectstatic将不会自动获取该文件。

See https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-STATICFILES_DIRS 请参阅https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-STATICFILES_DIRS


Confusion Surrounding Staticfiles 混淆周围的静态文件

There's always a lot of confusion around Django and Static files. Django和Static文件总是存在很多混乱。 I believe this confusion comes from the fact that it doesn't make any sense for Django to handle static files in production , but it seems natural to use it when learning to use Django and thus when initially developing. 我相信这种混淆来自于Django在生产中处理静态文件没有任何意义,但在学习使用Django并因此在最初开发时使用它似乎很自然。

The reason it doesn't make any sense for Django to serve static files is that Django is a framework for rendering dynamic responses . Django服务静态文件没有任何意义的原因是Django是一个渲染动态响应的框架。 "Static" files are not dynamic: they don't change. “静态”文件不是动态的:它们不会改变。 Thus, it's a huge waste of resources to spin up a Python application, which calls all of the Django machinery, just to find and return a file that has no dynamic content. 因此,创建一个调用所有Django机器的Python应用程序,只是为了找到并返回一个没有动态内容的文件,这是浪费大量资源。

Staticfiles: the job of the webserver Staticfiles:Web服务器的工作

There is something that is really good at serving static files: webservers themselves (such as a Apache, nginx, etc.). 有一些非常擅长提供静态文件:webservers本身(例如Apache,nginx等)。 That's what they were designed to do. 这就是他们的目的。 The webserver can run a Python/Django application or it can just locate a file and send it back, so you typically configure a webserver by telling it something like the following (in pseudo-server-speak): Web服务器可以运行Python / Django应用程序也可以只找到一个文件并将其发回,因此您通常会通过告诉它类似以下内容来配置Web服务器(在伪服务器中说话):

  • When someone accesses the path /static/ let them access the files in the following directory: /var/www/static/ . 当有人访问路径/static/让他们访问以下目录中的文件: /var/www/static/

  • When someone accesses the path / , spin up this Python application that lives over here: /var/www/django-app . 当有人访问路径/ ,启动这个生活在这里的Python应用程序: /var/www/django-app

Django Static Files Tools Django静态文件工具

As a result, Django comes with some helper tools that manage static files, so that your actual server can serve them. 因此,Django附带了一些管理静态文件的帮助工具,因此您的实际服务器可以为它们提供服务。

These tools are the following(defined in settings.py ): 这些工具如下(在settings.py定义):

  • STATIC_URL : the URL path where your server will be serving your static files. STATIC_URL :服务器将为静态文件提供服务的URL路径。 This is just so that when you use the static templatetag, that Django knows how to urlreverse it. 这只是为了当你使用static模板urlreverse时,Django知道如何对其进行urlreverse In other words, it's merely a convenient way of turning {% static "..." %} into /static/... . 换句话说,它只是将{% static "..." %}转换为/static/...的便捷方式。
  • STATIC_ROOT : the place on your server (or in the cloud somewhere), to which Django will copy your static files, so that your server can serve them. STATIC_ROOT :服务器上(或云中某处)的地方,Django 将复制静态文件,以便您的服务器可以为它们提供服务。 This copying happens when you run collectstatic . 运行collectstatic时会发生此复制。
  • STATICFILES_DIRS : any extra directories Django should look for static files whenever you run collectstatic . STATICFILES_DIRS :任何额外的目录Django应该在运行collectstatic时查找静态文件。 By default Django only looks in each app's directory for a static directory (just like with templates ). 默认情况下,Django只在每个应用程序的目录中查找static目录(就像使用templates )。

Static Files In Development 开发中的静态文件

Okay, but that's not so helpful in development where you are probably using Django's runserver command. 好的,但是在你可能正在使用Django的runserver命令的开发中没那么有用。 You don't have a server running that will server static files. 您没有运行服务器来服务静态文件。

Thus, you can ask Django to please also server static files for you in just this one case, because you are developing your application and don't want to run a separate server. 因此,在这种情况下,您可以 Django为您提供服务器静态文件,因为您正在开发应用程序而不想运行单独的服务器。

There is a view that automatically should pick up and serve static files when DEBUG=True . DEBUG=True时,有一个视图会自动拾取并提供静态文件。 Alternately, this is also why someone might use the following: 或者,这也是有人可能使用以下内容的原因:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

If I recall, you need to specify STATIC_ROOT = 'static' in settings.py and you need to have a URL to direct /static to your static files. 如果我记得,你需要在settings.py指定STATIC_ROOT = 'static' ,你需要有一个URL来指向/static到你的静态文件。 like so. 像这样。

urlpatterns += patterns('',
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.STATIC_ROOT, 'show_indexes': True
    }),
)

This could be a bit outdated but still works for me. 这可能有点过时,但仍然适用于我。

Also, are you trying to get this to work on your dev site with python manage.py runserver or on a production site? 另外,您是否尝试使用python manage.py runserver或在生产站点上使用dev网站?

Update 更新

Here is an example for you main urls.py file. 以下是主urls.py文件的示例。

from django.conf.urls import patterns, include, url

urlpatterns = (
    url(r'^admin/', include(admin.site.urls)),
    # more urls...
)

#The following enable structural 'static' files while in development mode.
if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT, 'show_indexes': True
        }),
    )

patterns is imported near the top of your urls.py file. 在urls.py文件的顶部附近导入patterns

This is where STATIC_ROOT comes in to play. 这就是STATIC_ROOT用武之地。

You may also need to run python manage.py collectstatic in order for your static files to be collected from your various apps and copied into the folder that is STATIC_ROOT . 您可能还需要运行python manage.py collectstatic ,以便从各种应用程序中收集静态文件并将其复制到STATIC_ROOT文件夹中。

See this answer for a much more in depth explanation :) 请参阅此答案以获得更深入的解释:)

I tried everything, nothing worked.我尝试了一切,没有任何效果。 In the end it turn out that image was corrupt because I opened it as bytes in Visual Code editor.最后结果证明图像已损坏,因为我在 Visual Code 编辑器中将其作为字节打开。

Uploaded new image and everything worked.上传了新图片,一切正常。

"

  1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS . 确保您的INSTALLED_APPS包含django.contrib.staticfiles
  2. In your settings file, define STATIC_URL, for example: STATIC_URL = '/static/' 在您的设置文件中,定义STATIC_URL,例如: STATIC_URL = '/static/'
  3. Hopes you stored images in folder /static/projectname/image.png 希望您将图像存储在文件夹/static/projectname/image.png
  4. Finally in your html simply add the following 最后在你的html中添加以下内容

<img src="/static/projectname/image.png" alt="My image"/>

please refer django dcumentation 请参考django dcumentation

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

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