来自数据库的图像未显示在Django模板中

时间:2020-07-16 18:45:51

标签: django django-templates image-upload image-rendering

我正在尝试通过模型的ImageField形式将图像存储在数据库中,该图像被上传到我创建的媒体文件夹中并在模板中呈现相同的图像。
这是我的文件夹结构- folder structure
这是我的settings.py文件-

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 3.0.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9q5awt($2rn+iwvku6p!r59st5a@g^%oqcc16=*v9s&-q_7=+n'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap3',
    'userAuth',
    'groups',
    'posts',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

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

MEDIA_ROOT=MEDIA_DIR
MEDIA_URL='/media/'

LOGIN_REDIRECT_URL = "/loggedin"
LOGOUT_REDIRECT_URL = "/loggedout"

这是我的发布应用程序的urls.py文件。仅通知一下,我有3个应用程序,即posts,groups,userAuth。

from django.conf.urls import url
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name='posts'

urlpatterns = [
    url(r"^$", views.PostList.as_view(), name="all"),
    url(r"new/in/(?P<pk>\d+)/$", views.CreatePost.as_view(), name="create1"),
    url(r"comment/in/(?P<pk>\d+)/$", views.CreateComment.as_view(), name="create2"),
    url(r"by/(?P<username>[-\w]+)/$",views.UserPosts.as_view(),name="for_user"),
    url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$",views.PostDetail.as_view(),name="single"),
    url(r"comment/delete/(?P<pk>\d+)/$",views.DeleteComment.as_view(),name="delete_comment"),
    url(r"delete/(?P<pk>\d+)/$",views.DeletePost.as_view(),name="delete"),
]
if settings.DEBUG: 
        urlpatterns += static(settings.MEDIA_URL, 
                              document_root=settings.MEDIA_ROOT)

这是post_detail.html,我要在其中渲染图像的模板(第8行)-

{% extends "posts/post_base.html" %}

{% block content %}
<div class="col-md-8">
    <div class="post media ">
        <div class="post media list-group-item" style="margin-top: 9px;"><h3 class="title list-group-item-heading" style="color: black !important; margin-bottom: 10px;font-size: large;">{{ post.question }}</h3></div>
        <div class="post media list-group-item" style="margin-top: 9px;"><h3 class="title list-group-item-heading" style="color: black !important; margin-bottom: 10px !important; font-size: medium;">{{ post.description_html|safe }}</h3></div>      
///line 8        <img src="{{MEDIA_URL}}/pics/{{ post.picture }}" class="img-responsive" style="width: 100%; float: left; margin-right: 10px;" alt="heyy"/> 
        <div class="media-body">
            <h5 class="media-heading" style="margin-top: 7px;">
                <span class="username"><a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a></span>
                <time class="time"><a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a></time>
            </h5>
    

当我在模板而不是第8行上打印{{post.picture}}时得到pics / download.jpg时,上传部分就可以正常工作了

这是我的帖子应用程序的models.py-

from django.conf import settings
from django.urls import reverse
from django.db import models

import misaka

from groups.models import  Group

from django.contrib.auth import get_user_model
User = get_user_model()


class Post(models.Model):
    user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    question = models.CharField(max_length=255)
    # question_html = models.TextField(editable=False)
    description=models.TextField(blank=True, default='')
    description_html = models.TextField(editable=False)
    picture=models.ImageField(upload_to='pics',blank=True)
    group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE,)

    def __str__(self):
        return self.question

    def save(self, *args, **kwargs):
        self.question_html = misaka.html(self.question)
        self.description_html = misaka.html(self.description)  
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse(
            "posts:single",
            kwargs={
                "username": self.user.username,
                "pk": self.pk
            }
        )

    class Meta:
        ordering = ["-created_at"]
        unique_together = ["user", "question"]

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments',on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    comment = models.TextField()
    text_html = models.TextField(editable=False)
    user = models.ForeignKey(User, related_name="comments",on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        self.text_html = misaka.html(self.comment)  
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        # return reverse("posts:single" , kwargs={"slug": self.slug})
        return reverse("posts:single" , kwargs={"username":self.post.user.username,"pk":self.post.pk})

    def __str__(self):
        return self.text


posts应用程序的forms.py-

from django import forms

from posts import models


class PostForm(forms.ModelForm):
    class Meta:
        # fields = ("message", "group")
        fields = ('question','description','picture')
        model = models.Post




class CommentForm(forms.ModelForm):
    class Meta:
        # fields = ("message", "group")
        fields = ('comment',)
        model = models.Comment

这是有关渲染的m个网页,也供参考,我在检查时打开了显示不同URL的元素-

webpage

我得到的是残破的图像和替代文本,而不是实际的图像。

0 个答案:

没有答案