问题
I want to view images, in a template, but I don't understand what I'm doing wrong.
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"
This is my template:
{% 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>
When I view the code in a browser, the path is correct:
But when I click on the URL, I see this:
It tells me that my picture doesn't exist, but it is there!
回答1:
Something that I would like to bring to your notice. static stores your css,js and images that are needed for the website frontend. media stores all the images uploaded by the user. So, in your settings define,
MEDIA_URL = 'media/'
Then, inside your template append /{{MEDIA_URL}} in front of {{item.photo}}.
And in your urls.py file, to the urlpatterns append:
+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This ought to sort the problem.
回答2:
You are not specifying the URL of the photo correctly. In your template, replace the line
<img src = "{{item.photo}}", width = "150", height = "250">
with
<img src = "{{item.photo.url}}", width = "150", height = "250">
回答3:
I think you haven't specified a media folder. In your settings.py you need this:
MEDIA_URL = '/media/'
MEDIA_ROOT = join(settings.PROJECT_ROOT, 'media')
And photos/to_trade should be inside this media folder. Also you need to use {{item.photo.url}} in your template instead of {{item.photo}}
来源:https://stackoverflow.com/questions/30626488/using-image-in-a-template-django