在搜索了几个小时但没有解决问题的解决方案之后,我发布了这个。来自我的媒体根目录的图片没有显示在我的html上。在chrome的控制台中,我得到一个404 file not found
。即使图像在那里。我在Pycharm中使用Python 3,Django 1.10。
这是模型,我将图片上传到:
from django.db import models
class Post(models.Model):
username = "anonymous"
post = models.ImageField(upload_to='anon')
creation_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return Post.username
views.py :
from django.shortcuts import render,get_object_or_404
from .models import Post
def home(request):
return render(request,"base.html",{})
def post_detail(request,id=None):
instance = get_object_or_404(Post,id=id)
context = {
"post": instance.post,
"instance": instance
}
return render(request,"post_detail.html",context)
post_detail.html (此处图片未显示):
<body>
<img src = "{{ instance.post.url}}" height="520" width="500"><br>
{{ instance.creation_date }}<br>
{{ instance.username }}<br>
</body>
setting.py 的部分内容:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Post',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Post.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'Post.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Post/media/')
我的目录是什么样的:
答案 0 :(得分:2)
混淆静态和媒体设置是一个常见的错误。在您的情况下,您实际处理的是用户上传的MEDIA而不是STATIC。
<img src = "{{ instance.post.url}}" height="520" width="500"><br>
最相关的设置是此处描述的MEDIA_ *设置 https://docs.djangoproject.com/en/1.10/howto/static-files/
但更重要的是,在您的开发服务器中,您需要通过添加
来启用MEDIA的传送from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)