1

我按照本教程将图像添加到我的 django 博客(教程链接:https ://www.youtube.com/watch?v=ygzGr51dbsY&list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi&index=26 )

但是当我发布博客文章时,图像不会显示 图像未显示

但是图像被保存在一个文件夹中

但是当我转到管理面板并单击帖子时,我看到了这个

当我点击当前位置时,我得到了这个

在此处输入图像描述

这是我的 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'

但是那家伙的 BASE_DIR 变量与我的不同。(我认为是因为他使用的是 django 2 而我使用的是 django 3)所以我将我的 BASE_DIR 变量散列出来并更改了 BASE_DIR 变量并将其从 DATABASES 字典中删除。

我的 urls.py 文件

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)

我的 add_post.html 文件

<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>

我的 detail_view.html 文件

<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 }}">

如果我忘记显示文件,请告诉我。

谢谢你。

4

1 回答 1

0

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

于 2021-01-08T15:09:29.573 回答