Search code examples
djangodjango-templatesdjango-staticfilesdjango-media

Using admin uploaded images


In admin page I add some image to model Product. In my settings.py file i write this:

MEDIA_ROOT = os.path.abspath('media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    ('static', os.path.abspath('static')),
)

Uploaded image is placed in folder media. I want to display these images and write in template next:<img src='{{ brand.product_image.url }}' alt=""/> and write{% load staticfiles %} in the template, but image is not displayed. What's the problem then? And one more question: what's the better way to store images that are uploaded by admin: in media folder or in static folder? And can I store images in app folder, where I use them?

My Brandmodel:

class Brand(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.CharField(max_length=1000)
    product_image = models.ImageField()
    def __unicode__(self):
        return self.name

My template code:

<div class="tab-pane  active" id="blockView">
        <ul class="thumbnails">
            {% for brand in brands %}
                <a href="{% url 'brand' brand_id=brand.id %}">
                <li class="span3">
                    <div class="thumbnail">
                    <img src='{{ brand.product_image.url }}' alt=""/>
                    <div class="caption">
                      <h5>{{ brand.name }}</h5>
                    </div>
                  </div>
                </li>
                </a>
            {% endfor %}
          </ul>
    <hr class="soft"/>
    </div>

Solution

  • Static and media files have different purpose. For uploaded files you should use media files. Static files are images, JavaScript, or CSS files which are included to your static template. So, if some images are part of your templates by default store they in static folder.

    About not displayed image: Please provide more information. Post your models.

    Update - serve media and static on development server.

    Update your urls.py

    from django.conf.urls import patterns, include, url
    from django.conf.urls.static import static
    from django.conf import settings
    
    
    from django.contrib import admin
    admin.autodiscover()
    
    
    urlpatterns = patterns(
        '',
    
    )  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=True) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT, show_indexes=True)