我是django的新手。我想製作上傳圖片並顯示來自數據庫的圖像,但我無法顯示圖像。我已經問過這個問題,但麻煩並沒有解決。如何在django中顯示圖像1.7
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殼和查詢數據檢查。結果是記錄數據。 你能幫我解決這個麻煩嗎?
什麼是生成的html中的src屬性的值?它是否爲空? – avs
是的,它是空的。怎麼樣? – User0511
'url(r'^ home/$','kerajinan.views.home',name ='home')' 你家的方法是什麼? 應該是'url(r'^ home/$','kerajinan.views.slider',name ='home')' – moonstruck