简体   繁体   English

Heroku Django 图像未加载

[英]Heroku Django Images not loading

Been trying to fix this a few hours, can't seem to wrap my head around it.几个小时以来一直试图解决这个问题,似乎无法解决这个问题。 I have whitenoise installed and the website works fine besides the images not loading.我安装了白噪声,除了图像未加载外,网站运行良好。 Here are my media codes:这是我的媒体代码:

├───.idea ├────.idea

├───analyst ├────分析师

│ └─── pycache │ └─── pycache

├───blog ├───博客

│ ├───migrations │ ├───迁移

│ │ └─── pycache │ │ └─── pycache

│ ├───static │ ├───静态

│ │ ├───blog │ │ ├───博客

│ │ └───images │ │ └───图片

│ ├───templates │ ├───模板

│ │ └───blog │ │ └───博客

│ └─── pycache │ └─── pycache

└───media └────媒体

└───article_pics └────article_pics

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

MAIN URLS:主要网址:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls'))
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Home Template:主页模板:

{% extends "blog/base.html" %}
{% load static %}
{% load crispy_forms_tags %}

{%block content%}
<!-- Images Section -->

<div class="swiper-container" style="height:520px;">
        <div class="swiper-wrapper">

            <section class="swiper-slide about two">
                <div class="container">
                    <div class="title title-dark">
                        <h2 class="title-heading">Analyze Everything</h2>
                        <img class="about-profile" src="{%static 'images/think.png'%}" alt="">
                        <p class="price"></p>
                    </div>
                    <div class="cta">

                    </div>
                </div>
            </section>

            <section class="swiper-slide about two">
                <div class="container">
                    <div class="title title-dark">
                        <h2 class="title-heading">Free Subscription</h2>
                        <h3 class="title-sub-heading">Read. Analyze. Learn.</h3>
                    </div>
                    <div class="cta">
                        <a href="#newsletter" class="btn btn-danger">Subscribe</a>
                    </div>
                </div>
            </section>


            </div>
     <div class="swiper-pagination"></div>
    <!-- Add Arrows -->
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>




</div>
<!-- End of Images Section -->

<!-- Latest Articles -->
<div class="container">
    <hr><br>
    <h1 class="text-center">Latest Articles</h1>
    <!-- Row One of Articles -->
    <div class="row">
        {%for articles in articles%}
          <div class="col-md-4 pt-4">
            <div class="card h-100">
                <img class="card-img-top" src="{{ articles.image.url }}" alt="Card image cap">
                <div class="card-body">
                    <a href="{% url 'article-detail' articles.id%}" class="article-title">{{articles.title}}</a>
                    <hr>
                    <p class="card-text">{{articles.content|safe|slice:":80"}}...</p>
                    <a class="btn btn-sm btn-outline-primary" href="{% url 'article-detail' articles.id%}">Read More...</a>
                </div>
            </div>
        </div>
        {%endfor%}
    </div>
    <!-- End of Row One of Articles -->


    <!-- Row Two of Articles -->
    <div class="row ">
        {% for articles_two in articles_two %}
          <div class="col-md-4 pt-4">
            <div class="card h-100">
                <img class="card-img-top" src="{{ articles_two.image.url }}" alt="Card image cap">
                <div class="card-body">
                    <a href="{% url 'article-detail' articles_two.id%}" class="article-title">{{articles_two.title}}</a><hr>
                    <p class="card-text">{{articles_two.content|safe|slice:":80"}}...</p>
                    <a class="btn btn-sm btn-outline-primary" href="{% url 'article-detail' articles_two.id%}">Read More...</a>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    <!-- End of Row Two of Articles -->

    <br>
    <a style="float:right;" href="{%url 'articles' %}" class="btn btn-warning"> <i class="fas fa-angle-double-right"></i></a>
</div>
<!-- End of Latest Articles -->

<br><br><hr>

<section id="newsletter" class="newsletter">
    <h1 class="text-center">Subscribe to The Analyst Now</h1>
    <p class="text-center mb-3" style="color: grey;">Subscribe For Automatic Updates.</p>
    <div class="text-center">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">{{form.as_p}}
                <button class="btn btn-danger" type="submit">Subscribe</button>
            </fieldset>
        </form>
    </div>
    <br>
</section>


    <!-- Javascript Tags -->
    <script src="{% static 'blog/swiper.min.js' %}"></script>
    <script>
        var swiper = new Swiper('.swiper-container', {
          effect: 'coverflow',
          grabCursor: true,
          centeredSlides: true,
          slidesPerView: '1',

          autoplay: {
            delay: 3000,
            disableOnInteraction: false,
          },

          coverflowEffect: {
            stretch: 0,
            depth: 100,
            modifier: 1,
            slideShadows : true,
          },

          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          },
          pagination: {
            el: '.swiper-pagination',
          },
        });
      </script>
{%endblock%}

I think there are a few things happening here:我认为这里发生了一些事情:

Static vs Media files Static 与媒体文件

Just to be clear about the difference... Static files are part of your codebase and include things like CSS files, JavaScript files and images that are used for the design of your site.只是要清楚区别... Static 文件是您的代码库的一部分,包括 CSS 文件、JavaScript 文件和用于您网站设计的图像等内容。 They only change when you do some development work.只有当您进行一些开发工作时,它们才会发生变化。

Media files are files uploaded to your site, either through the Admin, or through a form you've made that your users use.媒体文件是通过管理员或通过您制作的用户使用的表单上传到您网站的文件。 eg profile images, or covers of books, or images in a blog post.例如,个人资料图片、书籍封面或博客文章中的图片。

Because you have less control over Media files, they're often treated differently because there's a slightly higher security risk, and there might well be many more of them.由于您对媒体文件的控制较少,因此它们通常会受到不同的处理,因为安全风险略高,而且可能还有更多。

Local development地方发展

During local development (when you're using ./manage.py runserver ) Django's development server should serve both Static and Media files without problem.在本地开发期间(当您使用./manage.py runserver时)Django 的开发服务器应该毫无问题地同时提供 Static 和媒体文件。 You shouldn't need to use whitenoise when working locally.在本地工作时,您不需要使用白噪声。 If static and/or media files aren't loading then it's either because:如果 static 和/或媒体文件未加载,则可能是因为:

  • The paths in settings ( STATIC_ROOT , MEDIA_ROOT ) don't match up to the locations of your static and media directories, or设置中的路径( STATIC_ROOTMEDIA_ROOT )与您的 static 和媒体目录的位置不匹配,或者
  • There's an error in how you're trying to point to the files in your templates.您尝试指向模板中文件的方式存在错误。

So, during local development, are both static and media files not loading?那么,在本地开发过程中,static 和媒体文件都没有加载吗? Or just one or other?或者只是一个或另一个? View source of your page in the browser and look at the paths of the files there - are they what you'd expect?在浏览器中查看页面的源代码并查看那里的文件路径 - 它们是您所期望的吗?

Heroku Heroku

Heroku does not have a persistent file system, which means that it cannot serve Media files. Heroku 没有持久文件系统,这意味着它无法提供媒体文件。 So if you, or anyone, uploads a new file through a form on the website, while it might initially load as expected, because it's been saved to disk, very soon the file itself will disappear and will no longer load on the website.因此,如果您或任何人通过网站上的表单上传新文件,虽然它最初可能会按预期加载,因为它已保存到磁盘,但文件本身很快就会消失并且不再在网站上加载。 The only files that persist on disk are those that are part of your code repository.唯一保留在磁盘上的文件是那些属于您的代码存储库的文件。

You're right to be using whitenoise, but that will only serve your project's Static files.您使用白噪声是正确的,但这只会服务于您项目的 Static 文件。

To serve Media files you'll need to use django-storages and host the files elsewhere (like Amazon S3, or a different service django-storages supports).要提供媒体文件,您需要使用django-storages并将文件托管在其他地方(如 Amazon S3,或 django-storages 支持的不同服务)。 This is a real pain, and it's annoying that Heroku don't explain this in their documentation.这是一个真正的痛苦,令人讨厌的是 Heroku 没有在他们的文档中解释这一点。 There are guides for setting this up if you google (I've used this one before; I don't know if it's still valid).如果你用谷歌搜索的话,有一些设置指南(我以前用过这个;我不知道它是否仍然有效)。


Aside from the above, the main issue I see with your file structure at the moment is that article_pics is outside of media .除上述内容外,我目前在您的文件结构中看到的主要问题是article_picsmedia之外。 I assume you have a model ( Article ?) with an image field?我假设您有一个带有image字段的 model( Article ?)? And maybe you've set the field's upload_to parameter to article_pics ?也许您已将该字段的upload_to参数设置为article_pics In which case that directory should be within media .在这种情况下,该目录应该在media中。

When you add a new Article and upload an image, during development, can you see it in your filesystem?当您添加新文章并上传图片时,在开发过程中,您可以在文件系统中看到它吗? Where does it go?它在哪里 go?

The below has your media directory completely outside the project.下面的媒体目录完全在项目之外。

├───analyst

├───blog

│ ├───migrations

│ ├───static

│ │ ├───blog

│ │ └───images

│ ├───templates

│ │ └───blog

└───media

└───article_pics

Please try updating to the below and run collectstatic again:请尝试更新到以下内容并再次运行 collectstatic:

├───analyst

├───blog

│ ├───migrations

│ ├───static

│ │ ├───blog

│ │ └───images

│ ├───templates

│ │ └───blog

| └───media

| └───article_pics

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

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