python - 图像未出现在 django 2.1 的模板中
问题描述
我正在为我的网站制作个人资料页面。我在网上遵循了几个人的指示,我按照他们所说的做了(即 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
设置.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 %}
视图.py
@login_required
def Profile_view(request):
user = User
return render(request, 'index/profile.html', {'title': 'profile'}, {'user' : user})
我认为这是模板中的问题,但我不确定。当我尝试在管理员中打开图像时,它工作正常。
解决方案
你指定
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
推荐阅读
- android - SVG 文件在 Android Studio 中是否可扩展
- python - 如何在不使用字符串方法的情况下反转数字?
- excel - 列范围可以与 SUBSTITUTE 一起使用吗
- python - 如何使用 PyCharm 激活我的虚拟环境?我什至可以在 PyCharm 中激活它吗?
- gridsome - 单击按钮后调用 API
- javascript - 如何添加 4 位小数的输出结果?
- flutter - 带有不匹配参数的闭包调用:函数'LoginScreen.build。
- bash - 如何使用现有文件夹名称作为基本名称创建按顺序编号的文件夹列表
- python - django:如何从 View.py 读取和操作 .csv 文件
- flutter - 如何在 ListView 中显示来自实时数据库的数据?