Django不从媒体文件夹加载图像

时间:2018-07-01 06:41:56

标签: django python-3.x django-models django-templates

我已经写了一个基本的博客代码。在这种情况下,我尝试添加必须在屏幕上显示为封面图像的图像。但是图像未加载。

我的代码:

models.py

    from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.db import models



class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    poster = models.ImageField(upload_to=settings.MEDIA_ROOT);
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
                            unique_for_date='publish')
    author = models.ForeignKey(User,
                               on_delete=models.CASCADE,
                               related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
                              choices=STATUS_CHOICES,
                              default='draft')

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

urls.py:

    from django.conf import settings
from django.conf.urls import url,include
from django.conf.urls.static import static

from . import views

urlpatterns = [
    url(r'^$',views.post_list,name='post_list'),
]

urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

模板文件:

    {% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}

{% for post in posts %}
      <div class="row">

        <!-- Blog Entries Column -->
        <div class="col-md-8">
          <!-- Blog Post -->
          <div class="card mb-4">
            <img class="card-img-top" src="{{ post.poster }}" alt="Card image cap">
            <div class="card-body">
              <h2 class="card-title">{{ post.title }}</h2>
              <p class="card-text"></p>
              <a href="#" class="btn btn-primary">Read More &rarr;</a>
            </div>
            <div class="card-footer text-muted">
              {{ post.publish }} by {{post.author}}
            </div>
          </div>
{% endfor %}
{% endblock %}
          <!-- Pagination -->
          <ul class="pagination justify-content-center mb-4">
            <li class="page-item">
              <a class="page-link" href="#">&larr; Older</a>
            </li>
            <li class="page-item disabled">
              <a class="page-link" href="#">Newer &rarr;</a>
            </li>
          </ul>

        </div>
      </div>

错误日志:

[01/Jul/2018 12:03:00] "GET /20161216_120931.jpg HTTP/1.1" 404 2515
[01/Jul/2018 12:12:17] "GET / HTTP/1.1" 200 3659
[01/Jul/2018 12:12:17] "GET /static/blog/bootstrap.min.css HTTP/1.1" 304 0
Not Found: /20151215_113251.jpg
[01/Jul/2018 12:12:17] "GET /20151215_113251.jpg HTTP/1.1" 404 2515
[01/Jul/2018 12:12:17] "GET /static/blog/blog-home.css HTTP/1.1" 304 0
Not Found: /20161216_120931.jpg
[01/Jul/2018 12:12:17] "GET /20161216_120931.jpg HTTP/1.1" 404 2515

settings.py:

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

当我尝试显示图像时,未显示该图像。这是什么错误?如何纠正呢?我还在settings.py文件中添加了媒体根。图像被完美地存储在媒体文件夹中。但是,当我尝试显示图像时,出现404错误。请帮忙。预先感谢!

1 个答案:

答案 0 :(得分:1)

问题出在URL上。从日志中,您可以看到图像的URL只是/20161216_120931.jpg,而http://localhost/20161216_120931.jpg上没有这样的图像。实际网址应为/media/20161216_120931.jpg。您可以像这样在过滤器/media前面添加URL {{post.poster}}

{% for post in posts %}
  <div class="row">

    <!-- Blog Entries Column -->
    <div class="col-md-8">
      <!-- Blog Post -->
      <div class="card mb-4">
        <img class="card-img-top" src="{{ post.poster }}" alt="Card image cap">
        <div class="card-body">
          <h2 class="card-title">{{ post.title }}</h2>
          <p class="card-text"></p>
          <a href="#" class="btn btn-primary">Read More &rarr;</a>
        </div>
        <div class="card-footer text-muted">
          {{ post.publish }} by {{post.author}}
        </div>
      </div>
{% endfor %}

或者,如果您创建方法来为您添加网址,那就更好了。在您的 models.py 中:

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    poster = models.ImageField(upload_to=settings.MEDIA_ROOT);
    title = models.CharField(max_length=250)
    ...

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

    def get_absolute_image(self):
        return os.path.join('/media', self.poster.name)

然后在您的模板中输入:

{% for post in posts %}
  <div class="row">

    <!-- Blog Entries Column -->
    <div class="col-md-8">
      <!-- Blog Post -->
      <div class="card mb-4">
        <img class="card-img-top" src="{{ post.get_absolute_image }}" alt="Card image cap">
        <div class="card-body">
          <h2 class="card-title">{{ post.title }}</h2>
          <p class="card-text"></p>
          <a href="#" class="btn btn-primary">Read More &rarr;</a>
        </div>
        <div class="card-footer text-muted">
          {{ post.publish }} by {{post.author}}
        </div>
      </div>
{% endfor %}