无法在Django模板中显示图像(使用ImageField)

我正在将管理站点中的图像上传到模型的imagefield中。我已经对settings.py和urls.py文件进行了必要的更改,并在我的项目中添加了媒体目录。尽管图像显示在管理站点中,但是在渲染模板时出现“图像属性没有与之关联的文件”错误。

这是我的文件:

template(users.html)

<!DOCTYPE html>
{% load static %}
    <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="">
    </head>
    <body>
        <h1>Here are your users</h1>
        {% if user_list %}
            <ol>
                    {% for user in user_list %}
                <li> User Info</li>   
                    <ul>
                       <li>First Name:{{user.f_name}}</li> 
                        <li>Last Name:{{user.l_name}}</li>
                        <li>Email:{{user.email}}</li>
                        <li>Image:<img src="{{ user.image.url }}"></li>

                    </ul>
                    {% endfor %}
            </ol> 
        {% endif %}    




    </body>
</html>

models.py

from django.db import models

# Create your models here.

class User(models.Model):
    f_name=models.CharField(max_length=20)
    l_name=models.CharField(max_length=20)
    email=models.EmailField()
    image=models.ImageField(upload_to='pictures',null=True,blank=True)

    def __str__(self):
        return (self.f_name+" "+self.l_name)

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import User

# Create your views here.
def index(request):
    return HttpResponse("<em>My Second Project</em>")

def help(request):
    helpdict = {'help_insert':'HELP PAGE'}
    return render(request,'appTwo/help.html',context=helpdict)

def dispUsers(request):
    user=User.objects.order_by('f_name')
    user_dict={"user_list":user}
    return render(request,'appTwo/users.html',context=user_dict)

settings.py

"""
Django settings for ProTwo project.

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

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

For the full list of settings and their values,see
https://docs.djangoproject.com/en/2.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__)))

print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5$=@s-e_#2yzh+-nn^r!$0%l0%_n-)n(g-9w7f9b+x#@lrc_%%'

# 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','appTwo.apps.ApptwoConfig',]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [],'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 = 'ProTwo.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.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/2.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/2.0/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.0/howto/static-files/

STATIC_URL = '/static/'

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

urls.py

"""ProTwo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('',views.home,name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('',Home.as_view(),name='home')
Including another urlconf
    1. Import the include() function: from django.urls import include,path
    2. Add a URL to urlpatterns:  path('blog/',include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from appTwo import views
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    path('',views.index,name="index"),path('help/',include('appTwo.urls')),path('admin/',admin.site.urls),path('users/',views.dispUsers,name="users")
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Here's an image showing my diresctory structure

jjydjy 回答:无法在Django模板中显示图像(使用ImageField)

您的用户模型上有一个可选的图像字段。当然,您现在或以后会有一些没有与用户关联的图像的记录。因此,现在的模板将引发错误。您所要做的就是将条件放在模板中,以查看用户记录是否确实有与之关联的图像。

{% if user.image %}
    <img src="{{ user.image.url }}">
{% endif %}
,
upload_to='pictures/'

在图像字段中使用它 并请检查文件是否存储在图片目录中

,

像这样更改模型: image = models.ImageField(upload_to ='pictures /',null = True,blank = True) 并检查图片上传是否正确

本文链接:https://www.f2er.com/3148963.html

大家都在问