[英]Django: Displaying image from model field?
我無法顯示圖像。 這應該很容易解決。 我只是菜鳥。 :/
我的models.py是以下內容:
import datetime
from django.db import models
from django.utils import timezone
class Coin(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
ticker = models.CharField(max_length=5)
logo = models.ImageField(upload_to='uploads/', verbose_name='image')
website = models.URLField(max_length=200, default="https://example.com/")
reddit = models.URLField(max_length=200, default="https://reddit.com/r/")
twitter = models.URLField(max_length=200, default="https://twitter.com/")
summary = models.CharField(max_length=500, blank=True)
description = models.TextField()
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.ticker
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class CoinImage(models.Model):
coin = models.ForeignKey(Coin, default=None, related_name='images',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='static/uploads', verbose_name='image')
在我的views.py中,我有:
from django.http import HttpResponse, Http404
from django.template import loader
from django.shortcuts import render
from .models import Coin
def index(request):
latest_coins_list = Coin.objects.order_by('-pub_date')[:5]
context = {'latest_coins_list': latest_coins_list}
return render(request, 'coins/index.html', context)
def detail(request, coin_id):
try:
coin = Coin.objects.get(pk=coin_id)
except Coin.DoesNotExist:
raise Http404("Coin does not exist")
return render(request, 'coins/detail.html', {'coin': coin})
我的主要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('coins/', include('coins.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我的應用urls.py是:
from django.urls import path
from django.conf import settings
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:coin_id>/', views.detail, name='detail'),
]
然后最后在我的模板文件details.html中:
{% load static %}
<img src="{{ coin.logo.path }}" alt="La" />
<h1>{{ coin.name }} | {{ coin.ticker }}</h1>
<p>{{ coin.description }}</p>
<li><strong>Website:</strong> {{ coin.website }}</li>
<li><strong>Twitter:</strong> {{ coin.twitter }}</li>
<li><strong>Reddit:</strong> {{ coin.reddit }}</li>
當我查看模板時,我會看到替代文本。 然后,當嘗試直接訪問圖像127.0.0.1:8000/static/uploads/thumbs/me.jpg時,出現模板錯誤,提示:
找不到頁面(404)請求方法:GET請求URL: http : //127.0.0.1 :8000/static/uploads/thumbs/me.jpg提出者:django.views.static.serve
找不到“ uploads / thumbs / me.jpg”
您看到此錯誤是因為Django設置文件中的DEBUG = True。 將其更改為False,Django將顯示標准的404頁面。
這應該是一件非常簡單的事情。 如果有人能指出我正確的方向,我將非常感激。 對不起,是菜鳥。 :P
為某人添加:
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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i*a%3!kg*mj7j-=5b@_3cx(^%sqr*&sp$-fg*qv=qewm!a-_gt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'coins',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'blockintel.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 = 'blockintel.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/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
在開發過程中,您可以從MEDIA_ROOT
提供用戶上傳的媒體文件。 這是存放用戶上傳文件的目錄的絕對文件系統路徑。 在您的設置中,您應該提供:
# MEDIA_ROOT = os.path.join(BASE_DIR,'your_directory')
MEDIA_ROOT = os.path.join(BASE_DIR,'media') # media most of the time
MEDIA_URL
,用於處理從MEDIA_ROOT
的媒體的URL,用於管理存儲的文件。 如果設置為非空值,則必須以斜杠結尾。 您將需要配置這些文件以在開發和生產環境中提供。 在您的設置中添加
# MEDIA_URL = '/your_url/'
MEIDA_URL = '/media/' # most of the time
您還需要通過將以下代碼段添加到根urls.py中來執行此操作:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
注意:此輔助功能僅在調試中有效。 在這里了解更多
問題/建議
在此字段中,無需將文件上傳到static
目錄,只需提供您的媒體目錄即可,在這種情況下,它是media
。
image = models.ImageField(upload_to='uploads/', verbose_name='image')
里面“上傳”:Django會自動創建一個目錄MEDIA_ROOT
這是media
,
因此,訪問您擁有的所有圖像
# file.url
{{ coin.logo.url }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.