Problem loading image in user-uploaded images in Profile page

Hey everyone! I am a beginner to Django (version = 5.0) and I have issue in viewing user-uploaded content on their profile page that is being rendered on HTML. I have installed Pillow library properly and I tried all methods but I can’t seem to understand what the issue seems to be.

views.py

@login_required
def user_profile(request):
    return render(request, "register_user/profile.html")

urls.py

from django.urls import path
from register_user import views
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static

# url patterns 

app_name = 'register_user'

urlpatterns = [
    path("", views.index, name="register-index"),
    path("signup/", views.userRegister, name="register-user"),
    path("login/", auth_views.LoginView.as_view(template_name='register_user/login.html'), name="login"),
    # path("login/", views.login_user ,name="login"),
    path("profile/", views.user_profile, name="profile"),
    path("logout/", views.logout_user, name="logout"),
] 

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    image = models.ImageField(default = "default.jpg", upload_to='profile_pics')
    
    def __str__(self) -> str:
        return f"{self.user.username} Profile"

settings.py

STATIC_DIR = BASE_DIR / 'static'
STATIC_URL = "static/"
STATICFILES_DIRS = [STATIC_DIR,]

# MEDIA 
MEDIA_ROOT = BASE_DIR / "media"
MEDIA_URL = "media/"

profile.html

{% block content_block %}
   
  <div class="card border-light mb-3" >

    <img src="{{ user.profile.image.url }}" alt="Card image cap">
    <div class="card-header">Username ~ {{ user.username }}</div>
    <div class="card-body">
      <h5 class="card-title">{{user.first_name}} {{user.last_name}}</h5>
      <p class="card-title"> Your email -> {{user.email}} </p>
    </div>
  </div>

{% endblock content_block %}

I created a profile object through admin and uploaded an image. And then I tried displaying it through profile.html and it shows this error->

I have tried resizing the image to make it smaller and have also manually checked that the image is present in that folder by going to that directory. I am clueless, kindly help.

There’s something not matching up here.

You have:

But your log is showing references to /media/profile_imgs/ and not /media/profile_pics/

Which directory contains this file? What is the file name as shown in the directory listing?

Side note: Your upload_to and your MEDIA_ROOT entries are missing the trailing slash ‘/’ in their definitions. (See the referenced docs for the examples)

Side note 2: Please don’t post images of text when you can copy/paste the text into your posts - surrounded by the ``` like you have done with your code. (Thank you for that!)

Hello!
Yes I’m really sorry. I uploaded the wrong screenshot and I have upload_to = ‘profile_pics’

I tried applying your recommended fixes as follows:

image = models.ImageField(default = "default.jpg", upload_to='profile_pics/')

and

MEDIA_ROOT = BASE_DIR / "media/"

Still the issue persists and after trying to upload a different image, that image is not loading.

[14/Jan/2024 18:35:40] "GET /register/profile/ HTTP/1.1" 200 2750
Not Found: /media/profile_pics/HSBC-9c9da987_zNHegwD.png
[14/Jan/2024 18:35:40] "GET /media/profile_pics/HSBC-9c9da987_zNHegwD.png HTTP/1.1" 404 2492 

Is this in a production deployment or in your development environment using runserver? If you’re using runserver, what is your DEBUG setting?

What are the contents of your root urls.py file?

Please show that this file name exists in the appropriate directory.

The settings.py of my main project - test_project is -

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = BASE_DIR / 'templates'
STATIC_DIR = BASE_DIR / 'static'

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-h=0-^90y_o!&ol+hig_^w5i$at6l21_5#bt3d+51gc*3fca2e#"

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "crispy_forms",
    "crispy_bootstrap4",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

EXTERNAL_APPS = [
    "blog",
    "register_user",
]

INSTALLED_APPS += EXTERNAL_APPS

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 = "test_project.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [TEMPLATE_DIR,],
        "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 = "test_project.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

PASSWORD_HASHERS = [
    "django.contrib.auth.hashers.Argon2PasswordHasher",
    "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
]

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",
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "static/"
STATICFILES_DIRS = [STATIC_DIR,]

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# MEDIA 
MEDIA_ROOT = BASE_DIR / "media/"
MEDIA_URL = "media/"

# CRISPY FORMS
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap4"

CRISPY_TEMPLATE_PACK = "bootstrap4"

LOGIN_REDIRECT_URL = "blog:blog-content"
LOGIN_URL = "register_user:login"

By root urls.py I assume you are referring to urls.py of test_project app, which is -

from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include('blog.urls')),
    path("register/", include('register_user.urls')),
]

The path of the image which I want to display is →

C:\Users\PEYYETTI\My_Django_project\test_project\media\profile_pics\HSBC-9c9da987_zNHegwD.png

I am using a virtual environment which is myDjangoEnv in which I have installed Django 5.0.1 along with Python version 3.11.5

Ok, the issue here is that you’ve got your media urls being defined in the app instead of at the project level. The if settings.DEBUG block in your app’s urls should be in your root urls.py file.

(Yes, your “root” urls are the urls referred to by your settings.py file.)

1 Like

Yes, thankyou the issue has been solved. Thanks a lot again, I had been trying to solve the issue since yesterday!
Thank you again!