MEDIA_ROOT Django do not find images

守給你的承諾、 提交于 2019-12-13 07:12:26

问题


I want to display *.png images on my template but can`t ! All other page's stuff renders well (bootstrap on http path, css from local files). I waste few hours trying to set path but no effect. Seems I tried all I could invent. Please help.

please see project tree

settings.py

... 
import os
 '''path settings for django==1.8'''
# BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)))

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

TEMPLATE_DIRS = (
    #'/Users/jmitch/Desktop/seven/static/templates/',
    os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), "static", "templates"),
)

TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            # 'DIRS': [BASE_DIR+"/templates", ],
            'DIRS': [BASE_DIR + "/static/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',
                    'django.core.context_processors.media',
                ],
            },
        },
    ]
ENV_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media')
# MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'static', 'media')
# MEDIA_ROOT = '/Volumes/Storage/_codework/e_shop/static/media/product/images/'
# MEDIA_ROOT = os.path.join(BASE_DIR,"media/images")
MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'static', 'static-only')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'static', 'static'),
)

      ...

all.html

    .....    
 {% block content %}

  {% for product in products %}
      <div class='container-fluid'>
      <div class='col-md-6'>{{ product.title }}
      {{ product.price }}

      {% for image in product.productimage_set.all %}
           <img src ='{{ "MEDIA_URL" }}{{ image }}'/>
      </div>
      {% endfor %}
      </div>
  {% endfor %}
            {{ image }}
  {% endblock %}
  .......

ecommerce/urls.py

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.STATIC_ROOT
        }),
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.MEDIA_ROOT
        }),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^products/', include('products.urls')),
    url(r'^contact/', 'contact.views.contact_us', name='contact_us'),
)

products/urls.py

from django.conf import settings
from django.conf.urls import patterns, include, url

urlpatterns = patterns('products.views',

   url(r'$', 'all_products', name='products'),

  )

models.py

    from django.db import models


class Product(models.Model):
    title = models.CharField(max_length=220)
    description = models.CharField(max_length=3000, null=True, blank=True)
    price = models.DecimalField(max_digits=1000, decimal_places=2, null=True, blank=True)
    slug = models.SlugField()
    active = models.BooleanField(default=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)


    def __unicode__(self):
        return self.title

    ''' sort item alphabetically '''
    class Meta:
        ordering = ['title']

class ProductImage(models.Model):
    product = models.ForeignKey(Product)
    description = models.CharField(max_length=3000, null=True, blank=True)
    image = models.ImageField(upload_to='/product/images')
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)


    def __unicode__(self):
        return self.image

回答1:


<img src ='{{ "MEDIA_URL" }}{{ image }}'/>

is wrong. You need

<img src ='{{ MEDIA_URL }}{{ image }}'/>

or

<img src ='{{ image.url }}'/>

Since ImageField inherits all methods and attributes of FileField, you have an access to FileField property called .url which calls the url() method of Storage class. It will return the relative path including /media/ folder.



来源:https://stackoverflow.com/questions/33592380/media-root-django-do-not-find-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!