Media files not displaying on template


#1

My end goal and main focus of the current website is to display images on a template that a user can upload through the admin page. Seems pretty simple, but I’m having trouble getting them to show up… Any suggestions? I’d be happy to upload any code necessary. Thanks!!!


#2

First off, in general it’s a bad idea (if I recall correctly) to give users access to the Django admin. It’s famously hard to modify. Might be better to create a user dashboard?

Regardless of that — are you using the Hello Web App books or is this in general? (I have a section on user uploaded images in the Intermediate book, not sure if you’ve seen it.)


#3

Thanks for the quick reply, Tracy! I am using the HWA books, and have moved onto the intermediate book. Ill go back through the 4th chapter and see if I can’t sniff out what’s going on.A user dashboard sounds promising…

FWIW, the site I’m making is a pretty simple couple of pages that will ultimately display my wife’s art in rows and columns of her custom work. She won’t need to register users, as it will be only her and I that will need access. But I’d like her to be able to easily upload pictures that will display on a template without having to go into the code at all. I will add some other features from your book (contact page, possibly adding a payment system down the road) but most of what you teach I will use on other ideas I have.


#4

Still no luck getting the images to show up on the template. Here is what I have thus far (indentation didn’t copy correctly):

models:
from future import unicode_literals
from django.conf import settings

from django.db import models

from PIL import ImageFile

Created Model for Pictures to be added

class Picture(models.Model):
name = models.CharField(max_length=250)
description = models.TextField()
medium = models.CharField(max_length=50)
slug = models.SlugField(unique=True)

def get_absolute_url(self):
    return "/picture/%s/" % self.slug

def __str__(self):
    return self.name

def get_image_path(instance, filename):
return '/'.join(['media', instance.picture.slug, filename])

class Upload(models.Model):
picture = models.ForeignKey(Picture, on_delete=models.CASCADE, 
related_name="uploads")
image = models.ImageField(upload_to='')

views:

def index(request):
pictures = Picture.objects.all()
return render(request, 'index.html', {
    'pictures': pictures,
})

def pictures_detail(request):
pictures = Picture.objects.all()
uploads = Picture.uploads.all()

return render(request, 'pictures_detail.html', {
    'uploads': uploads,
})

urls:

urlpatterns = [
path('', views.index, name='home'),
path('about/', TemplateView.as_view(template_name='about.html'), name='about'),
path('contact/', views.contact, name='contact'),
path('pictures_detail/', 
TemplateView.as_view(template_name='pictures_detail.html'),             
name='pictures_detail'),
path('admin/', admin.site.urls),
*static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT),
]

if settings.DEBUG:
urlpatterns += [
    re_path(r'^media/(?P<path>.*)$', serve, {
        'document_root': settings.MEDIA_ROOT,
    }),
]

and admin:

class PictureAdmin(admin.ModelAdmin):
model = Picture
list_display = ('name', 'description', 'medium',)
prepopulated_fields = {'slug': ('name',)}

class UploadAdmin(admin.ModelAdmin):
list_display  = ('picture',)
list_display_links = ('picture',)

#Register Model
admin.site.register(Picture, PictureAdmin)
admin.site.register(Upload, UploadAdmin)

and the html page:

{% extends 'base.html' %}
{% load staticfiles %}
{% load static %}

{% block title %}
Works of Art - {{ block.super }}
{% endblock title %}


{% block content %}

  <section class="row">
    <div class="grid">

{% for upload in uploads %}

      <img src="{{ upload.image.url }}" alt="" />

{% endfor %}

    </div>
  </section>

{% endblock %}

The template is simply rendering empty :(


#5

a) Could be because of an indentation issue, and unfortunately I can’t check for that here. Could you possibly put on pastebin.com or share a link to a public repository (like on Github)?

b) Template shouldn’t show anything unless you have uploads. Do you indeed have images uploaded? Do they show up in the admin?


#6

Indentation seems to be correct within my files (I haven’t gotten any issues otherwise).

I do have 2 .jpgs uploaded to the admin which are showing up. They are located within the “media” directory, which is in the same spot as manage.py.

https://github.com/ZeffGoldblum/JessNewlin_Art/tree/TemplateRender


#7

Kind of hard for me to diagnose, unfortunately! Can you put your code on a public repo so I can take a look at it all?


#8

Were you able to access the master branch? The rest of what I’ve done is there…


#9

Sigh, sorry, I completely glossed over Discourse’s Github preview, didn’t realize it was a link. Looking now though I am stepping out soon so I’ll try to respond tomorrow!


#10

You changed the pathing code here from what was in the book, from “object_images” to “media”: https://github.com/ZeffGoldblum/JessNewlin_Art/blob/TemplateRender/collection/models.py#L24

(IC code: https://github.com/hellowebbooks/hellowebapp-ic-code/blob/master/collection/models.py#L50)

As the images will be in the “media” folder already, I’m wondering if this is creating confusion for Django on where to find the images. How do they show up on your system?


#11

Still no luck.

def get_image_path(instance, filename):
     return '/'.join(['picture_images', instance.thing.slug, filename])

class Upload(models.Model):
    thing = models.ForeignKey(Thing,
        on_delete=models.CASCADE, related_name="uploads")
 image = models.ImageField(upload_to='media')

A few different things I tried: in the ‘upload_to:’ attribute within the image field, I tried a few different paths, namely: ‘get_image_path’, which created a new directory for each photo uploaded within picture_images directory which was within the media directory. Looked like this:

media
>>>>picture_images
    >>>>Keller
        >>>>keller.jpg

I changed the get_image_path attribute to ‘media’ and all photos are now pathed thusly:

media
>>>>media
    >>>>keller.jpg

I also just left the field blank, like:

upload_to:'',

which put all media files into the first media directory…

media
>>>>keller.jpg

Regardless, still no luck. Maybe Ill just delete the whole project and start over ;) Thanks for taking the time to help!


#12

Don’t delete the project! This is good learning experience. :)

If I was in your shoes, I would make a new, shell project, and just try to do the chapter completely verbatim and see if you can get it to work and if there are any differences.

Oh, another thing — if the images are showing up in the admin, can you right click and get the full image URL? Does it differ from what get_image_path is generating? That can also give you a clue to what might be wrong.


#13

I entered the additional code of picture.name and picture.description into my pictures_detail.html file to see if anything would show up (similar to what you have in your examples) with no luck:

{{ picture.name }}

{{ picture.description }}

    <section class="row">
    <div class="grid">

{% for upload in uploads %}

      <img src="{{ upload.image.url }}" alt="" />

Nothing is showing up when I have entered this either, so I’m beginning to think there may be something wrong with the html pages…? All code mimics what you have done in the books, but Im not able to display anything.


#14

FYI I want to investigate this more but I’m traveling. Please keep at it and I’ll try to get to this as soon as I can!