python - 如何在 Django 中显示来自模型的图像

标签 python django image upload

需要说明的是,我已经尝试自己研究这个问题,但由于我对 Django 还是很陌生,所以我无法理解这里的解决方案。我也阅读了文档,但我不明白我做错了什么。我无法让位于“ad_pictures”目录中的图像显示在 HTML 中。

这是我的代码:

设置.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'),
]

模型.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”。 非常感谢任何见解。

谢谢

最佳答案

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

关于python - 如何在 Django 中显示来自模型的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732028/

相关文章:

安装 Homebrew Python 后 Python 包在错误的位置?

python - Django 的基本 URL,在 Nginx 代理后面

html - 打印 (Cocoa) WebView 内容会生成剪切图像

python - django:避免在 get_or_create 上出现 "Unused variable"警告

Django + Pydev/Eclipse + Google App Engine - 可能吗?

javascript - 在不使用 Jquery 推送其他图像的情况下,在鼠标悬停时放大图像?

Python:未安装 _imagingft C 模块

python - 为什么 Selenium 不点击?(Python)

python - OpenCV:错误:(-215:断言失败)函数 'cv::equalizeHist' 中的 _src.type() == CV_8UC1

python - 如何从 Python/Perl 在 Exchange 2010 中创建 Exchange 邮箱