在模板django中使用图像

时间:2015-06-03 17:09:43

标签: django django-templates

我想在模板中查看图片,但我不明白我做错了什么。

Image not displayed (correctly)

models.py

class Item(models.Model):
    name = models.CharField(verbose_name = "Название", max_length = 100)
    TYPE_ITEMS = (
        ("shirt", "Футболка"),
        ("shoes", "Обувь"),
        ("bags", "Рюкзаки и сумки"),
        ("heads", "Головные уборы"),
        ("others", "Другое"),
        )
    type_item = models.CharField(verbose_name = "Тип продукта",
                                 choices = TYPE_ITEMS, max_length = 6,
                                 default = "shirt")
    other = models.CharField("другая информация", max_length = 200)
    color = models.CharField("Цвет(а)", max_length = 100)
    cost = models.IntegerField("Стоимость за штуку", default = 0)
    is_available_now = models.BooleanField("Есть ли в наличии?",
                                           default = False)
    available_count = models.IntegerField("Количество в наличии", default = 0)
    photo = models.ImageField("Фото", upload_to = "photos/to_trade")

    def __str__(self):
        return self.name + " " + self.color + " (" + str(self.cost) + " грн)"

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader ####
from myapp.models import Item

def index(request):
    return render(request, "index.html")

def goods(request):
    shirts_list = Item.objects.filter(type_item = "shirt")

    template = loader.get_template("goods.html")
    context = RequestContext(request, {
        "shirts_list": shirts_list,})
    return HttpResponse(template.render(context))

def contacts(request):
    return render(request, "contacts.html")

def delivery(request):
    return render(request, "delivery.html")

urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

from myapp import views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'paporotnik.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', views.index, name = "index"),
    url(r'^goods', views.goods, name = "goods"),
    url(r'^contacts', views.contacts, name = "contacts"),
    url(r'^delivery', views.delivery, name = "delivery"),
    url(r'^photos/to_trade/(?P<path>.*)$', 'django.views.static.serve'),
)

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

SECRET_KEY = '(=bk@zukikdq==0dtokjbg-sbgge5zi(^te01+9=w%is-76sxv'
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

TEMPLATE_DIRS = [os.path.join(BASE_DIR, "templates")]

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'paporotnik.urls'

WSGI_APPLICATION = 'paporotnik.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = "C:\\Python33\\Scripts\\paporotnik\\static" 

这是我的模板:

{% load staticfiles %}

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset = "utf-8">
        <title>Товары - Paporotnik.ua</title>
        <link rel = "stylesheet", type = "text/css", href = "{% static 'myapp/style_index.css' %}">
    </head>
    <body>
        <div id="container">
            <!-- Верхняя панель (заголовок) -->
            <div id="header">
                <div style = "float: left; width:100%">
                    <div style = "margin: 0 10%;">
                        <br><h1 id = "heed">Paporotnik.ua</h1><br>
                    </div>
                </div>
                <div id = "divLogo">
                    <img id = "logo", width = "125", height = "125">
                </div>
                <div id = "trash" align = "center">
                    <h3>Корзина</h3>
                    <img align = "center", width = "70", height = "50">
                </div>
            </div>
            <!-- Центр, основное содержимое -->
            <div id="wrapper">
                <div id="content">
                    <p align = "center">
                    <h2 align = "center">Футболки</h2>
                    <div align = "center">
                        {% for item in shirts_list %}
                            <img src = "{{item.photo}}", width = "150", height = "250">
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

当我在浏览器中查看代码时,路径是正确的:

Path in Browser

但是当我点击URL时,我看到了:

Error message

它告诉我,我的照片不存在,但它就在那里!

Local path

3 个答案:

答案 0 :(得分:2)

我想提醒您注意的事项。 static存储网站前端所需的css,js和图像。 media存储用户上传的所有图像。因此,在您的设置中定义

MEDIA_URL = 'media/'

然后,在您的模板中,在/{{MEDIA_URL}}前面添加{{item.photo}}

在你的urls.py文件中,添加到urlpatterns:

+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

这应该解决问题。

答案 1 :(得分:0)

您没有正确指定照片的网址。在模板中,替换

<img src = "{{item.photo}}", width = "150", height = "250">

<img src = "{{item.photo.url}}", width = "150", height = "250">

答案 2 :(得分:0)

我认为您还没有指定media文件夹。在您的settings.py中,您需要这个:

MEDIA_URL = '/media/'
MEDIA_ROOT = join(settings.PROJECT_ROOT, 'media')

photos/to_trade应位于此media文件夹中。您还需要在模板中使用{{item.photo.url}}而不是{{item.photo}}