图像未出现在 django 2.1 的模板中

Posted

技术标签:

【中文标题】图像未出现在 django 2.1 的模板中【英文标题】:Image not appearing in template in django 2.1 【发布时间】:2019-03-12 13:11:46 【问题描述】:

full file tree

我正在为我的网站制作个人资料页面。我在网上按照几个人的指示做了他们所说的(即 media_url、media_root、对我的 urls.py 的更改)。我通过管理页面注册了我的超级用户,并为它提供了个人资料。尝试获取我的图像时,它不显示。这是我的代码:

模型.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    Pic = models.ImageField(default='default.png', blank=True, upload_to='img')
    address = models.CharField(max_length=70, default='Bensons', unique=True)
    email = models.EmailField(max_length=70, unique=True, default='ben@email.com')

    def __str__(self):

        return self.address

settings.py

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


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=ytl^8!j@t(^c5eile%%x(l3hvkekc$z#_t538+%a)p2uvsr!+'

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

ALLOWED_HOSTS = ['192.168.1.192']

STATIC_URL = '/static/'

# Application definition

INSTALLED_APPS = [
    'crispy_forms',
    'index.apps.IndexConfig',
    'django.contrib.admin',
    'django.contrib.auth', #yoohoo
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts.apps.AccountsConfig',
]

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 = 'campaign.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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 = 'campaign.wsgi.application'

LOGIN_REDIRECT_URL = 'index'

LOGOUT_REDIRECT_URL = 'index'
# Database
# https://docs.djangoproject.com/en/2.1/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/2.1/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/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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


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

网站/urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('index.urls')),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls'))
]

urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

模板/profile.html

% extends 'index/base.html' %

% block content %
  <div class='container'>

    <img src=' user.Profile.Pic.url ' width='240'

  </div>
% endblock %

view.py

@login_required
def Profile_view(request):
    user = User

    return render(request, 'index/profile.html', 'title': 'profile', 'user' : user)

我认为这是模板中的问题,但我不确定。当我尝试在管理员中打开图像时,它工作正常。

【问题讨论】:

检查图像元素并检查图像的路径并验证该路径中是否存在图像 还有img 缺少结束标签 当我检查元素时它说 图片来源未知,因为你的表Profile中没有名为url的列;而不是 user.Profile.url 你必须写 user.Profile.pic.url 您在Pic中添加了图片,因此图片路径是user.profile.Pic.url而不是user.profile.url 【参考方案1】:

尝试在命令终端中使用此命令安装枕头: pip install pillow

【讨论】:

【参考方案2】:

你指定了

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# <----There doesn't seem to be a url field on the model
Pic = models.ImageField(default='default.png', blank=True, upload_to='img')
address = models.CharField(max_length=70, default='Bensons', unique=True)
email = models.EmailField(max_length=70, unique=True, default='ben@email.com')

def __str__(self):

    return self.address

模板

改变

<img src=' user.Profile.url ' width='240' />

<img src=' user.Profile.Pic.url ' width='240' />

https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.FileField.storage

【讨论】:

“url 字段”是什么意思 user.Profile.url 不是您的配置文件模型上的图像字段 如何添加 @abhinavchavali ‘url’ 给出了存储在 media/img 文件夹中的图像的相对路径 @KeshavGarg 它仍然无法正常工作。我的设置、网址或视图是否有问题

以上是关于图像未出现在 django 2.1 的模板中的主要内容,如果未能解决你的问题,请参考以下文章

媒体文件夹中的图像未显示 django 模板

“渲染占位符”未出现在 django CMS 模板中

ModelForm 的 Django 编辑模板未填充值

图像不出现 Django 模板

无法在引导程序中对齐图像

我的 Django 网站上的图像未加载