Django:从模型字段显示图像?

时间:2018-05-12 21:36:42

标签: python django python-3.x django-models django-templates

我无法显示图像。这应该很容易修复。我只是个菜鸟。 :/

我的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')

1 个答案:

答案 0 :(得分:0)

在开发过程中,您可以从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提供的媒体的网址,用于管理存储的文件。如果设置为非空值,则必须以斜杠结尾。您需要配置这些文件以在开发和生产环境中提供。在您的设置中添加此内容

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

注意:此帮助程序功能仅适用于调试。 Know more here

问题/建议

在此字段中,不要将文件上传到static目录,只需提供您的媒体目录,在这种情况下,它是media

image = models.ImageField(upload_to='uploads/', verbose_name='image')

Django将自动创建一个目录:MEDIA_ROOT内的'{uploads',media

因此,使用

访问您拥有的所有图像
# file.url 
{{ coin.logo.url }}