简体   繁体   中英

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

├───analyst

│ └─── pycache

├───blog

│ ├───migrations

│ │ └─── pycache

│ ├───static

│ │ ├───blog

│ │ └───images

│ ├───templates

│ │ └───blog

│ └─── pycache

└───media

└───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

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. 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. You shouldn't need to use whitenoise when working locally. If static and/or media files aren't loading then it's either because:

  • The paths in settings ( STATIC_ROOT , MEDIA_ROOT ) don't match up to the locations of your static and media directories, or
  • 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? 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 does not have a persistent file system, which means that it cannot serve Media files. 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.

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). This is a real pain, and it's annoying that Heroku don't explain this in their documentation. 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 . I assume you have a model ( Article ?) with an image field? And maybe you've set the field's upload_to parameter to article_pics ? In which case that directory should be within media .

When you add a new Article and upload an image, during development, can you see it in your filesystem? Where does it 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:

├───analyst

├───blog

│ ├───migrations

│ ├───static

│ │ ├───blog

│ │ └───images

│ ├───templates

│ │ └───blog

| └───media

| └───article_pics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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