1
votes

FIXED This was my solution, in the main programs urls.py I had to add these lines.

from django.conf import settings from django.conf.urls.static import static

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

I have an model called Item within there I have an image field. I added an new item with an image to the database and tried loading it inside of my index template. However I dont get an image when I look at the console it says ("WEBSITENAME/site_media/items/image.jpg 404 (Not Found)")

I think the problem lies within the settings.py file but I cant figure out what exactly I did wrong here.

index.html template

{% load static %}
<div class="item" style="background-image: url('{{ item.img.url }}')">`

Model.py

class Item(models.Model):
    name = models.CharField(max_length=200)
    img = models.ImageField(upload_to='items', default='', blank=True, null=True)

    def __str__(self):
        return "%s" % (self.name)

Views.py

def index(request):
    latestItems = Item.objects.all().order_by('-id')[:3][::-1]
    return render(request, 'webshop/index.html', {'latestItems' :latestItems})

settings.py

SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'site_media/')
MEDIA_URL = 'site_media/'
3
I managed to fix it. I had to add these lines in the main urls.py file: from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) - DjangoPleb1234
Please keep in mind, to be safe, you might add: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) - Jon

3 Answers

0
votes

In your settings.py

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'

and read this document

With the directory root structure that you have shown, I think the above setting should work. Have not tested it though. Let me know if it works.

0
votes

you have:

upload_to='items'

but:

{{ item.img.url }}

should that be?

{{ items.img.url }}
0
votes

in settings.py:

PROJECT_ROOT = os.path.abspath(os.path.dirname(__ file __))

STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "static"), )