【问题标题】:Django : Media Files not displayed in templatesDjango:媒体文件未显示在模板中
【发布时间】:2021-01-11 08:43:22
【问题描述】:

我正在尝试创建博客并在网页上显示用户上传的图像。当我使用 Django 管理界面上传图像文件时(我使用 ImageField 为发布图像制作了模型),图像正确存储在 /media/images 中。但我无法在我的网页上显示图像。但是,当我使用 GoogleChrome 检查模板时,我的文件路径正常,但出现 500 错误(加载资源失败:服务器响应状态为 500(内部服务器错误)。

媒体设置.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'


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


STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'core/static'),
    )

项目 urls.py:

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


urlpatterns = [
    path('admin' , admin.site.urls),
    path("", include("authentication.urls")),
    path("", include("app.urls")),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

应用 urls.py:

from django.urls import path, re_path
from django.conf.urls import include, url

from app import views
from . import views

  

urlpatterns = [
    path('', views.index, name='home'),
    url(r'^blog$', views.blog_view, name ='blog'),
    url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'),
    re_path(r'^.*\.*', views.pages, name='pages'),
]

Views.py

def blog_view(request):
    query = Post.objects.all().order_by('-date')
    context = {'post_list' : query}
    return render(request, 'blog/blog.html', context)

模板:Blog.html

{% for post in post_list %}
<img src="{{ post.image.url }}" class="card-img-top rounded-top">
{% endfor %}  

models.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=255, blank=True)
    image = models.ImageField(blank=True, upload_to="images/")

当我在 google chrome 控制台中检查时,我注意到我的开发服务器尝试将我的 jpg 文件读取为 txt 文件,我认为我的问题与此异常有关。有人知道如何解决我的问题吗?

【问题讨论】:

    标签: django django-models imagefield


    【解决方案1】:

    你可以这样做

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

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      • 2020-04-12
      • 2018-08-27
      • 2021-03-02
      • 2019-04-19
      • 2019-04-15
      相关资源
      最近更新 更多