Django显示未找到的图像

时间:2018-11-22 04:54:10

标签: python django

这已经让我发疯了2天了,我找不到答案。我浏览了无数的帖子,无法使它正常工作。

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

由于某种原因,即使我看到图像文件的路径是正确的,它也会继续显示404错误。

例如:

我的模特:

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文件夹中。

视图:

@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)

到我的网址文件。

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

正如我说的那样,我已经为此苦苦挣扎了两天,这可能是我完成该项目的最后一件事,但是我不明白出了什么问题。

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

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

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 = '/'

1 个答案:

答案 0 :(得分:2)

将此添加到您项目的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