0
votes

A beginner building a personal blog. Got a simple model with an ImageField. No matter what I try the Django won't serve an image.

Judging by the console output in the Dev Tools it is looking for an image in the wrong folder. I don't know how to fix that. I tried setting up MEDIA_URL, MEDIA_ROOT and adding a urlpattern like it's being suggest here and here

I have uploaded the picture via admin panel, its location is media/images/stockmarket.jpg. But for some reason the server is looking for an image here /blog/images/stockmarket.jpg

Project name: 'wikb', 'blog' is an App: project_file_system

models.py

from django.db import models

class Post(models.Model):
    title = models.CharField('Post Title', max_length=200)
    preview = models.CharField('Post Preview', max_length=400)
    thumbnail = models.ImageField('Post Picture', upload_to='images/', blank=True)

view.py

from django.shortcuts import render
from django.http import HttpResponse

from .models import Post

def home(request):
    all_posts = Post.objects.all()
    hero_post = all_posts[0]
    context = {'hero_post': hero_post, 'all_posts': all_posts}
    return render(request, 'blog/home.html', context=context)

HTML

<div class="hero">
    <a href="#" class="hero__link" style="background-image: url({{hero_post.thumbnail}})">
        <article class="hero__article">
            <h2 class="hero__heading">{{hero_post.title}}</h2>
            <p class="hero__preview">{{hero_post.preview}}</p>
        </article>
    </a>
</div>

settings.py

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

Global urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

It's my first Django project, please explain like I'm 5.

Update: I forgot to add .url when I referenced an object in templates.

1
Are you getting any errors?Kshitij Saxena
only this one: [13/Sep/2019 14:04:11] "GET /blog/media/images/stockmarket.jpg HTTP/1.1" 404 2314 Not Found: /blog/images/stockmarket.jpgPatrick Bateman
I believe you URL should be /media/... not /blog/media/...Kshitij Saxena
You assigned two upload_to parameters in ImageField why ?Moha369
Yes. But that's what django is trying to serve and I don't know how to change that.Patrick Bateman

1 Answers

3
votes

In templates, you'll want to use .url to get the real URL of a FieldFile (the file contained by a FileField or ImageField):

<a href="#" class="hero__link" style="background-image: url({{ hero_post.thumbnail.url }})">