Greg Strydom
Greg Strydom

Reputation: 159

Django Displaying Images Not Found

This has been driving me crazy for 2 days now and I cannot find an answer to this. I have looked through countless posts and cannot get this to work.

I am trying to display a profile picture for a user using Django ImageField in my model.

For some reason it keeps on coming up with 404 not found, even though I can see that the path to the image file is correct.

For example:

My model:

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

This is indeed uploading the image file to the media/profile_pics folder in my root directory.

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

The static and media settings in my settings file:

STATIC_URL = '/static/'

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

And I have added:

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

to my urls file.

It just gives an error of 404 not found, even when I check the source in Chrome or Firefox I can see that correct path is being shown. If I try and click on the image in the source to go to http://127.0.0.1:8000/media/profile_pics/default.jpg I get an error of 404 not found, so Django is clearly not finding the file even though the path is correct.

As I said I have struggling with this for 2 days now and is probably the last thing I need to finish this project off, but I cannot understand what is going wrong.

I would happy to provide further information if required and thank you for any help.

EDIT: I have included my full settings file.

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

Upvotes: 1

Views: 1014

Answers (1)

Bidhan Majhi
Bidhan Majhi

Reputation: 1370

Add this in your project's 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

Upvotes: 2

Related Questions