Я загружаю изображение с сайта администратора в поле изображения модели. Я внес необходимые изменения в файл settings.py и urls.py и добавил каталог мультимедиа в свой проект. Хотя изображение отображается на сайте администратора, я получаю ошибку «Атрибут 'image' не связан с файлом» при отображении шаблона.
вот мои файлы:
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)
Вот изображение, показывающее мою директивную структуру