Image uploaded to database but not displaying

62 views
Skip to first unread message

Michael Starr

unread,
Apr 12, 2023, 2:00:56 AM4/12/23
to Django users
I am finding that the url of files stored in a database with Django is automated to /media/[filename], which is neat, because that keeps it organized and from images being everywhere. However, only the alt text of my file shows--the url is correct but the image doesn't show. I've tried using static, as well as just {{ image.url }} and neither method worked for me. Also, which method is correct? Can we frikkin decide already? :P

Thank you.
Michael

David Nugent

unread,
Apr 12, 2023, 2:58:23 AM4/12/23
to django...@googlegroups.com
It is very important to understand the difference between “static” and “media”. The two are somewhat similar, and the code to handle (serve) each is even almost identical. Conceptually though they are quite different things.

static files are assets provided by your app and served to satisfy the direct needs of your app - e.g. javascript, css and other assets which never change, updated or rendered.
media files are more fluid things, usually uploaded or processed files, objects delivered by the application that are not a core part of rendering web pages.

Both STATIC_URL and MEDIA_URL are set up in your settings. In production, either or both may be served externally to django.

By default, MEDIA serving is not configured in Django settings, but there are many mentions of static files with a dozen or so possible configuration items. These are there because such configuration is important right at the start of developing a Django app.

If you need information on media handling though, you need to go back to the Django docs as there are no hints on how to do this in the default generated configuration.

The point is - do not confuse the two, and definitely do not try to tangle both as it will eventually lead to problems. Configure media separately from static and you will not encounter any of those problems, especially so when you get to deploying to production where you may wish to handle them differently (serving from cloud vs locally and choice of what served each etc and a myriad of other choices).

So, back to your problem, I would guess that you are simply missing a url handler for your media files at path(‘media/‘,…(, and the path stored in your db is almost definitely correct. The handler you will probably use in development mode will look something like your dev static files config, except for MEDIA_URL and pointing to the file system location where they are actually being uploaded.

HTH,
David
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4d1c1c52-c4d8-4f46-8333-adc673095fc1n%40googlegroups.com.

Chelsea Fan

unread,
Apr 12, 2023, 3:21:28 AM4/12/23
to django...@googlegroups.com
can see your settings.py and urls.py inside project folder? 

Michael Starr

unread,
Apr 12, 2023, 4:20:23 PM4/12/23
to Django users
Thank you for the perspective, David. That is good to know--that media and static are so different. Yes, in engineering, a separation of functions is often beneficial to the system. Same with software, I suppose.
However, the Django docs on managing files at https://docs.djangoproject.com/en/4.1/topics/files/ are very thin, tbh. They don't even display an example of rendering a user-uploaded image. They just do some REPL-type stuff. I am, as far as the extent of my knowledge goes, following the instructions on media_root and media_url, and they make it seem like it should be really simple. Either that or they're leaving out huge chunks of logic. I wouldn't put it past them that it be the latter.
And for all those involved and the lord and savior, I am not yet on production. FYI.

Michael

Michael Starr

unread,
Apr 12, 2023, 4:21:23 PM4/12/23
to Django users
settings.py
"""
Django settings for pet_memorial project.

Generated by 'django-admin startproject' using Django 2.2.12.

For more information on this file, see

For the full list of settings and their values, see
"""

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


# Quick-start development settings - unsuitable for production

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1eovl-=7pwb6e1*c7y@6@s7n0+ig)mxos2im3b_+^%3+rdze&k'

# 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',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pet_profile'
]

# Static files (CSS, JavaScript, Images)

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


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


TEMPLATE_PROJECT_DIR = os.path.join(BASE_DIR,'pet_memorial/templates/pet_memorial/')
TEMPLATE_APP_DIR = os.path.join(BASE_DIR,'pet_profile/templates/pet_profile/')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_PROJECT_DIR, TEMPLATE_APP_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 = 'pet_memorial.wsgi.application'


# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True





urls.py (in project folder)
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', views.HomeView.as_view(), name='home_view'),
    path('', include('pet_profile.urls')),
]

urls.py (in app folder)
from django.contrib import admin
from django.urls import path
from pet_profile import views

urlpatterns = [
    path("pet/<slug:slug>/", views.PetDetailView.as_view(), name = "pet_profile"),
    path("owner/<slug:slug>/", views.PetOwnerDetailView.as_view(), name = "owner_profile"),
]

Michael Starr

unread,
Apr 12, 2023, 4:22:50 PM4/12/23
to Django users
I checked my settings.py folder backward and forward; nothing seems odd. The media_root and media_url are very self-explanatory, and correct afaik.
And if you're going to tell me to add static url stuff to my urls.py, read what David said above.
Michael

Michael Starr

unread,
Apr 12, 2023, 4:27:34 PM4/12/23
to Django users
The photo app is registered in my admin file as well:
from django.contrib import admin
from .models import *

# Register your models here.
admin.site.register(PetOwner)
admin.site.register(Pet)
admin.site.register(PetPhoto)
admin.site.register(PetStory)

Michael Starr

unread,
Apr 12, 2023, 4:38:01 PM4/12/23
to Django users
media not displaying - Django.png

template
{% extends "base.html" %}
{% block header %}
{% endblock %}
{% block content %}
{% load static %}
    {{ owner.name }}
    {{ owner.age }}
    {{ owner.location }}
    {{ owner.profile_photo }}
    {% for pet in owner.pets.all %}
        {{ pet.name }}
        {{ pet.animaltype }}
        {{ pet.age }}
        <!-- context['pet_photos'] = {pet1: [photo1, photo2, photo3], pet2: [photo1, photo2]} -->
        <h1>{{ pet.name }} Photos</h1>
        {% for pet, pet_photos in pet_data.items %}
            <h2>{{ pet.name }}</h2>
            {% for pet_photo in pet_photos %}
                {{ pet_photo.photo.url }}
                <img src="{{ pet_photo.photo.url }}" alt="{{ pet_photo.title }}">
            {% endfor %}
        {% endfor %}
    {% endfor %}
{% endblock %}


base.html
<!DOCTYPE html>
{% load static %}
<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boot...@5.3.0-alpha1/dist/css/bootstrap.min.css" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="../../../static/styles.css">
    {% block header %}
    {% endblock %}
</head>
<body>
    <div class="container">
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home</a>
                    </li>
                    <!-- organize the navbar code and reduce the complexity of the example items in it -->
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            My Pets
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Action</a>
                            <a class="dropdown-item" href="#">Another action</a>
                        <div class="dropdown-divider"></div>
                            <a class="dropdown-item" href="#">Something else here</a>
                        </div>
                    </li>

                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Friends
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Action</a>
                            <a class="dropdown-item" href="#">Another action</a>
                        <div class="dropdown-divider"></div>
                            <a class="dropdown-item" href="#">Something else here</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>
    </div>
    {% block content %}
    {% endblock %}
    <script src="https://cdn.jsdelivr.net/npm/boot...@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</body>
</html>
Reply all
Reply to author
Forward
0 new messages