如何在django 1.7中显示图像

时间:2015-05-05 06:28:54

标签: python django

我是django的新手。我想制作上传图片并从数据库显示图片,但我无法显示图片。我已经问过了,但问题没有解决。

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 %}

我已经检查了python manage.py shell和查询数据。结果是记录数据。 你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

注意:

  

MEDIA_URL&amp; STATIC_URL设置必须具有不同的值

除了static/images以外,您可以提供任何您喜欢的内容other/imageslife/images等等......将会有效...

为什么这么多混淆......

实际建议的方式来提供媒体

MEDIA_URL = '/media/'

并在您的网址中删除静态服务并执行...

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

还有一件事将render_to_response更改为render