在 django 的 html 上查看从管理员上传的图片

view images uploaded from admin on html in django

我正在学习编写一个 Django 应用程序,它将从 os.path.join(BASE_DIR, 'media_root', 'uploads') 获取所有图像并将其显示在 html页。

但它不是这样工作的。

admin.py

from .models import Experience
# Register your models here.
admin.site.register(Experience)

settings.py

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

models.py

class Experience(models.Model):
    id = models.AutoField(primary_key=True)
    image = models.ImageField(upload_to='uploads/', default='newbalance.jpg', height_field=None, width_field=None)
    studio_name = models.CharField(max_length=255)
    designation = models.CharField(max_length=255)
    duration = models.CharField(max_length=255)
    description_short = models.TextField()
    description_long = models.TextField()
    keywords = models.CharField(max_length=255)
    date = models.DateTimeField('DateAdded',
             auto_now=True, auto_now_add=False)

    class Meta:
        db_table = "experience"

    def __str__(self):
        return self.studio_name + ' ' + self.duration

views.py

class ExperienceList(generic.ListView):
    model = Experience
    template_name = 'resumesection.html'
    queryset = Experience.objects.all()

urls.py

urlpatterns = [
    path('modelview/', views.ExperienceList.as_view(), name='experience_list'),
]

在错误日志中,

2021-07-19 04:15:40,528: Not Found: /resume_site/modelview/uploads/atomic_arts.png
2021-07-19 04:15:41,239: Not Found: /resume_site/modelview/uploads/futureworks.jpg

我认为 django 应该从 'MEDIA_ROOT/uploads' 文件夹中读取图像,但它是从“/resume_site/modelview/uploads/”中读取的。哪个不存在。

我在这个postDjango admin view uploaded photo中接近答案了, 但是无法连接 'MEDIA_ROOT/uploads' 和 '/resume_site/modelview/uploads/'

之间的点

如何在 django 中查看从管理员上传的图像。 ?

编辑:上下文resumesection.html的一部分

{% for exp in object_list %}
    <h5>{{exp.studio_name}} | {{exp.duration}}</h5>
    <img src="{{exp.image}}">
    <p id="description_short_text">
        {{exp.description_short}}
    </p>
    <p id="text" style="display:none;color:red">
        {{exp.description_long}}
    </p>
    <h4 id='keywords_text' style="display:block;color:green">KEYWORDS</h4>
    <p id='alt_text' style="display:block;color:green">{{exp.keywords}}</p>
{% endfor %}

urls.py 在项目中

urlpatterns = [
    path('admin/', admin.site.urls),
    path('barefoot/', include('barefoot.urls')),
    path('resume_site/', include('resume_site.urls')),
    path('photo_gallery/', include('photo_gallery.urls')),    
]

if settings.DEBUG:    # added
    import debug_toolbar
    urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

如果你想从数据库中获取文件并想放在 src 中,你必须在 last

中提供 .url

所以使用这个

<img src="{{ exp.image.url }}">

而不是

<img src="{{exp.image}}">

阅读此内容以更好地理解 https://docs.djangoproject.com/en/3.2/topics/files/ 告诉我你是否仍然收到错误