Django : Media Images not displayed in templates

Viewed 454

I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error).

Media Settings.py

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

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'


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


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

Project urls.py:

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


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

App urls.py:

rom django.urls import path, re_path
from django.conf.urls import include, url

from app import views
from . import views

  

urlpatterns = [
    path('', views.index, name='home'),
    url(r'^blog$', views.blog_view, name ='blog'),
    url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'),
    re_path(r'^.*\.*', views.pages, name='pages'),
]

Views.py

def blog_view(request):
    query = Post.objects.all().order_by('-date')
    context = {'post_list' : query}
    return render(request, 'blog/blog.html', context)

template : Blog.html

{% for post in post_list %}
<img src="{{ post.image.url }}" class="card-img-top rounded-top">
{% endfor %}                                    

models.py


class Post(models.Model):
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=255, blank=True)
    image = models.ImageField(blank=True, upload_to="images/")

1 Answers

Try this approach:

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

You can then find images under:

<img src="media/test.png">

The folder "media" is in the main dir of the Project (not the app!):

Project

  • media
  • static
  • APP
    • templates
    • views.py
Related