Search code examples
pythondjangodjango-2.2django-file-upload

django: uploaded images won't be displayed


my uploaded images can't be displayed even though i'm not getting any errors: instead it looks like this

and here are my settings and codes:

settings.py:

    STATIC_URL = '/static/'


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static_cdn")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"media")

models:

class Post (models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
cover = models.ImageField(null=True, blank=True, upload_to='media/')

urls:

if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views:

def posts_create (request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
    instance = form.save(commit=False)
    instance.save()
    messages.success(request, "Successfully created")
    return HttpResponseRedirect(instance.get_absolute_url())
context = {'form': form}
return render(request, 'post_form.html', context)

template:

{% extends "base.html" %}

 {% block title %} {{object.title}} | {{block.super}}{% endblock title%}

{% block content %}
<div class="center" style=" display: table; margin-right: auto; margin-left: auto;">
{% if object.cover %}
    <img src="{{object.cover.url}}" class="img-responsive"/>
{% endif %}
    <h1>{{title}} <small style="font-size: small"> {{object.timestamp}}</small> </h1>
    {{object.content | linebreaks}}<br>

<div/>
{% endblock content%}


Solution

  • I had the urls for static and media files in posts/urls not the main urls file, once I relocated them the issue disappeared.