【问题标题】:Retrieve image from django从 django 中检索图像
【发布时间】:2020-07-31 18:30:16
【问题描述】:

我是 Django 的初学者,正在尝试制作一个表格,该表格从 Django 数据库中获取数据(包含图像)。在 Django 模型中添加图像字段之前,这里一切正常。但我无法从 Django 媒体文件中获取图像(我还上传了具有超级用户和 Django 表单的图像,并且它们工作得很好)。下面是我的方法-

views.py 中:

def index(request):
    table_data = TableA.objects.order_by('roll')
    index_dict = {'insert_me' : "hello this is from views.py",
                  'dynamic_table' : table_data,
                 }
    return render(request, 'app26/index.html', context=index_dict)

HTML中:

    {% if dynamic_table %}
      <table class="table table-striped">
        <thead class="thead-dark">
          <tr>
            <th>Name</th>
            <th>Roll</th>
                    <th>Email</th>
          <th>Password</th>
          <th>Address</th>
          <th>Profile Pic</th>
          </tr>
        </thead>
        <tbody>
                {% for i in dynamic_table %}
          <tr>
            <td>{{ i.name }}</td>
            <td>{{ i.roll }}</td>
            <td>{{ i.email }}</td>
                    <td>{{ i.password }}</td>
          <td>{{ i.address }}</td>
          <td><img class="profile-pic" src="{{media_url}}{{ i.profile_pic }}" alt=""></td>
          </tr>
                {% endfor %}

        </tbody>
      </table>
        {% else %}
        <p>sorry cannot load the data for technical error</p>
        {% endif %}

urls.py

from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

我还设置了 MEDIA_URL 和 MEDIA_ROOT。从管理员我可以上传图片,它们没问题。 在 settings.py

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

现在我的问题是表格的个人资料图片列中没有显示任何内容,甚至没有显示任何错误。 请建议我如何从数据库中获取图像文件以供我使用

【问题讨论】:

    标签: django-media


    【解决方案1】:

    我认为图像未显示的主要原因是您的 media_url 的路径未添加到 render 函数中。见下文:

    def index(request):
        img = Upload.objects.filter(file_type='image')
        index_dict = {
                  'insert_me' : "hello this is from views.py",
                  'dynamic_table' : table_data,
                  'media_url': settings.MEDIA_URL
                  }
        return render(request, 'app26/index.html', context=index_dict)
    

    试一试!

    【讨论】:

    • 很高兴听到这个消息!
    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 2013-04-25
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多