User0511
User0511

Reputation: 725

How to Show Image in django 1.7

I am newbie in django. I would like to make upload image and to show image from database, but I am not able to show image. I already asked this but the trouble is not solved.

model.py:

class Static(models.Model):
    title           = models.CharField(max_length=50)
    description     = models.TextField()
    images1         = models.ImageField(upload_to="slider")
    images2         = models.ImageField(upload_to="slider")

    def __str__(self):
        return self.title

view.py:

def home(request):
sliders     = Static.objects.all()
posts       = Product.objects.all().order_by("-created_date")
paginator   = Paginator(posts,6)
page        = request.GET.get('page')

try:
    posts = paginator.page(page)
except PageNotAnInteger:
    posts = paginator.page(1)
except (InvalidPage, EmptyPage):
    posts = paginator.page(paginator.num_pages)

return render(request, 'kerajinan/home.html', {
    'posts'         : posts,
    'sliders'       : sliders,
    'categories'    : Category.objects.all(),
})

settings.py:

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/')
MEDIA_URL  = '/static/images/'

urls.py:

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

urlpatterns = patterns('',
    url(r'^home/$', 'kerajinan.views.home', name='home'),
)

if settings.DEBUG:
   urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

home.html

{% for i in sliders %}
        <div class="item active">
            <div class="col-sm-6">
                <h2>{{i.title}}</h2>
                <p>{{i.description}}</p>
                <button type="button" class="btn btn-default get">Get it now</button>
            </div>
            <div class="col-sm-6">
                <img src="{{ i.images1.url }}" class="girl img-responsive" alt="" />
                <img src="{{ i.images2.url }}" class="pricing" alt="" />
            </div>
        </div>
    {% endfor %}

I already checked in python manage.py shell and query data. The result is record data. Can you help me to solve this trouble?

Upvotes: 0

Views: 118

Answers (1)

Raja Simon
Raja Simon

Reputation: 10305

Note:

MEDIA_URL & STATIC_URL settings must have different values

so other than static/images give anything you like other/images or life/images etc... will work..

Why the so much confuses...

Actually recommended way to give media

MEDIA_URL = '/media/'

and in your urls remove the static serve and do ...

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

And one more thing change the render_to_response to render

Upvotes: 2

Related Questions