python - Django 显示未找到的图像

标签 python django

这两天已经让我发疯了,但我找不到答案。我浏览了无数帖子,但无法使其发挥作用。

我正在尝试在模型中使用 Django ImageField 显示用户的个人资料图片。

由于某种原因,即使我可以看到图像文件的路径是正确的,它仍然会出现 404 not found。

例如:

我的模型:

class KPILead(models.Model):
name            = models.CharField(max_length=255)
position        = models.CharField(max_length=255)
company         = models.ForeignKey(KPICompany)
profile_pic     = models.ImageField(upload_to='profile_pics/')

def __str__(self):
    return self.name

这确实是将图像文件上传到我的根目录中的 media/profile_pics 文件夹中。

View :

@login_required(login_url='/')
def eftlead_detail(request, eftlead_id):
    context = dict()
    context['eftlead'] = KPILead.objects.get(pk=eftlead_id)
    context['team_names'] = KPITeam.objects.filter(eft_lead__id=eftlead_id)
    context['incidents'] = KPIIncidentReport.objects.filter(eft_lead__id=eftlead_id)
    context['image_url'] = context['eftlead'].profile_pic.url
    return render(request, 'templates/eftlead.html', context)

我的设置文件中的静态和媒体设置:

STATIC_URL = '/static/'

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

我添加了:

 + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

到我的网址文件。

它只是给出了 404 未找到的错误,即使我在 Chrome 或 Firefox 中检查源代码,我也可以看到显示了正确的路径。如果我尝试单击源中的图像以转到 http://127.0.0.1:8000/media/profile_pics/default.jpg我收到 404 not found 错误,因此 Django 显然没有找到该文件,即使路径是正确的。

正如我所说,我已经为此奋斗了 2 天,这可能是我完成该项目所需的最后一件事,但我不明白出了什么问题。

如果需要,我很乐意提供更多信息,并感谢您的帮助。

编辑:我已经包含了完整的设置文件。

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q#-jd#zkg7+#2-=6pjy(%vg-%=sh%c1*c%ypu&uxz0-4cm-9^p'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

USE_DJANGO_JQUERY = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'base.apps.BaseConfig',
    'projects.apps.ProjectsConfig',
    'kpi.apps.KpiConfig',
    'smart_selects'
]

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 = 'gregweb.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates', 'kpi'],
        'APP_DIRS': True,
        'OPTIONS': {
            '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 = 'gregweb.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase'
    }
}

AUTH_PASSWORD_VALIDATORS = [
{
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Africa/Johannesburg'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

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

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,  'templates'),
)

LOGIN_REDIRECT_URL = '/kpi'
LOGOUT_REDIRECT_URL = '/'

最佳答案

将其添加到项目的 urls.py 中

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) #not both

关于python - Django 显示未找到的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53424109/

相关文章:

Django REST - 序列化 User.get_all_permissions

python - 在 IIS 上设置 Django

python 临时文件| NamedTemporaryFile 不能使用生成的临时文件

python - 查找数组一中最接近数组二元素的元素

python - 我怎样才能改变我的代码来反转某些子字符串?

python - SQLite Python 中的变量替换

python - XGBoost特征重要性: How do I get original variable names after encoding

python - 过滤 Django 数据库中包含数组中任何值的字段

python - 将 Django OAuth2 提供程序与 JupyterHub 结合使用

python - 在 Django REST 中增加计数器字段的最佳位置