Django blog not displaying images

133 Views Asked by At

I followed this tutorial on adding images to my django blog (tutorial link: https://www.youtube.com/watch?v=ygzGr51dbsY&list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi&index=26)

But when I post a blog post the image doesn't get displayed Image is not getting displayed

But the image gets saved in a folder

But when I go to the admin panel and click on the post I see this

when I click on the currently location I get this

enter image description here

This is my settings.py

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.

# BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': BASE_DIR / 'db.sqlite3',
        'NAME': 'db.sqlite3',
    }
}

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

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

STATIC_FILE_DIRS = (
    os.path.join(BASE_DIR, 'static')
)

LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

But that guys BASE_DIR variable was different than mine.(I think cause he is using django 2 and I am using django 3) So I hashed mine out and changed the BASE_DIR variable and removed it from the DATABASES dictionary.

My urls.py file

urlpatterns = [
    path('register/', UserRegisterView.as_view(), name='register'),
    path('edit_profile/', UserEditView.as_view(), name='edit_profile'),
    # path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html')),
    path('password/', PasswordsChangeView.as_view(template_name='registration/change-password.html'), name='change-password'),
    path('password_success/', password_success, name='password-success')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

My add_post.html file

<head>
    <title>Add Post...</title>
</head>

<h1>Add Blog Post...</h1>
<br/><br/>

<div class="form-group">
    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.media }}
        {{ form.as_p }}
        <button class="btn btn-secondary">Post</button>
    </form>
</div>

My detail_view.html file

<h1>{{ post.title }}</h1>
<small>By: {{ post.author.first_name }}
       {{ post.author.last_name }} -
       {{ post.post_date }}
    {% if user.is_superuser or user.is_staff and post.author.id == user.id %}
        <a href="{% url 'update_post' post.pk %}">(Edit)</a> <a href="{% url 'delete_post' post.pk %}">(Delete)</a> <br/>
    {% endif %}
    <hr>
</small>

<img src="{{ post.header_image.url }}">

If I forgot to display the file please tell me.

Thank you.

1

There are 1 best solutions below

0
On

I fond the problem. I need to add the + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my main urls.py