Search code examples
djangodjango-templatesdjango-media

Django 1.9: Unable to see uploaded photos


I have some photos uploaded but I was unable to see photos in temeplates

My template

{% extends 'base.html' %}
{% load staticfiles %}

{% block content %}
  <div class="row ">
    <div class="col-md-8">
      <h1>{{ object.title }}</h1>
          {% if object.productimage_set.count > 0 %}
        <div>
            {% for img in object.productimage_set.all %}
            {{ img.image.file }}
            {{ img.image.url }}
        <img class='img-responsive' src='{{ img.image.url }}' />
        </div>
      {% endfor %}
        </div>
      {% endif %}
    <div class="lead">{{ object.description }}</div>
    </div>
  </div>

My model

class Product(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(decimal_places=2, max_digits=20)
    active = models.BooleanField(default=True)

def __unicode__(self):  # def __str__(self):
    return self.title

class ProductImage(models.Model):
    product = models.ForeignKey(Product)
    image = models.ImageField(upload_to='product/')

Setting for media

    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "static", "my_static"),
    ]
    STATIC_ROOT =  os.path.join(BASE_DIR, "static", "static_root")
    STATIC_URL = '/media/media_root/'
    MEDIA_ROOT =  os.path.join(BASE_DIR, "static", "media_root")

My urls

urlpatterns = [
 url(r'^contact/', views.contact, name='contact'),
 url(r'^$', views.ProductViewList.as_view(), name='ProductViewList'),
 url(r'^(?P<pk>\d+)/$', views.ProductDetailView.as_view(), name='Product_Detail'),]

My folder structure

enter image description here

In the template {{ img.image.url }} gives -> product/mp3.jpg. But still I'm unable to see the image

The console shows that image is loaded from http://127.0.0.1:8080/product/1/product/mp3.jpg I guess there is some prob with the url to collect the image but not sure

Any help is much appreciated....Thanks in advance


Solution

  • You should add the MEDIA_URL to your settings.py, if you haven't.

    In your case, the MEDIA_URL should be media_root. My Image links all have /media/....jpg.

    In addition, you can specify the URLs:

    from django.conf import settings
    
    if settings.DEBUG:
        # static files (images, css, javascript, etc.)
        urlpatterns += patterns('',
            (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT}))