如何在Django中显示模型中的图像

时间:2018-06-07 02:09:02

标签: python django image upload

要说清楚,我已经尝试过自己研究这个问题但是因为我还是Django的新手,所以我无法理解这里的解决方案。我也阅读了文档,我不明白我做错了什么。我无法将位于“ad_pictures”目录中的图像显示在HTML中。

这是我的代码:

settings.py

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

urls.py(项目)

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

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls')),
    url(r'^classifieds/', include('classifieds.urls')),

 ] +static(settings.MEDIA_URL, document_ROOT=settings.MEDIA_ROOT)

urls.py(分类应用)

from django.conf.urls import url
from . import views

app_name = 'classifieds'

urlpatterns = [
    url(r'^create/', views.create, name='create'),
    url(r'^latestads/', views.latestads, name='latestads'),
]

models.py

class Post(models.Model):

    title = models.CharField(max_length=150)
    price = models.CharField(max_length=100)
    body = models.TextField()
    pub_date = models.DateTimeField(null=True)
    author = models.ForeignKey(User, null=True)
    category = models.CharField(max_length=150, null=True)
    picture = models.ImageField(upload_to='ad_pictures', default='')

latestads.html

            {% for post in posts.all %}
            <div class="advertisements">
              <div class="a-title">
                <h3><a href="">{{ post.title }}</a></h3>
              </div>
              <div class="a-image">
                <a href=""><img src="{{ post.picture.url }}"></a>
              </div>
              <div class="a-content">
                <p>{{ post.body }}</p>
              </div>
              <div class="a-date">
                <p>{{ post.pub_date }} by {{ post.author }}</p>
              </div>
            </div>
            <img src="{{ post.image.url }}">
            {% endfor %}

目录结构图片: here

Html输出: here

我确信问题的一部分是HTML中的“post.picture.url”。 非常感谢任何见解。

由于

1 个答案:

答案 0 :(得分:3)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls')),
    url(r'^classifieds/', include('classifieds.urls')),

 ] +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

请将document_ROOT更改为document_root